Simon Kröger
1/4/2006 7:54:00 PM
dblack@wobblini.net wrote:
> Hi --
>
> On Thu, 5 Jan 2006, James Edward Gray II wrote:
>
>> On Jan 4, 2006, at 12:46 PM, phil swenson wrote:
>>
>>> I have a hash that looks like this : {"1"=>"0, "3"="1", "45"=>"1",
>>> "101"=>"0"}
>>>
>>> What I want is an array of all the keys that have hash values equal to
>>> "1" ["3","45"] in this case.
>>>
>>> Yeah, i can just iterate the keys... but it seems like there is a "ruby"
>>> way to do this. Any thoughts?
>>
>>
>>>> h = Hash[*%w{1 0 3 1 45 1 101 0}]
>>
>> => {"45"=>"1", "1"=>"0", "101"=>"0", "3"=>"1"}
>>
>>>> h.select { |key, value| value == "1" }.map { |key, value| key }
>>
>> => ["45", "3"]
>
>
> Wouldn't it be easier to iterate through the keys? I'm not sure why
> Phil didn't want to. (Phil?)
>
> h.keys.select {|k| h[k] == 1}
>
>
> David
Don't know, but here is another one:
h.select{|k, v| v == "1" }.transpose.first
cheers
Simon