Find has key from a value

Hi,

I cant seem to figure this out, if i have a hash value can i then get
the key thats associated to that value.

So the hash.has_value(val)? method will return true or false if that
value exists in the hash but what i need to know is what is the key for
the particular value.

Any ideas?

JB

So the hash.has_value(val)? method will return true or false if that

value exists in the hash but what i need to know is what is the key for

the particular value.

Any ideas?

Yup, consider using Hash#invert or Hash#each_pair.

The invert method returns a new hash where the key-value mappings have
been
inverted. For example:

some_hash = {:a => 1, :b => 2, :c => 3}
another_hash = some_hash.invert # gives {1 => :a, 2 => :b, 3 => :c}
key_for_value = another_hash[2] # gives :b

Each_pair is a lot like each because it allows you to iterate through
the
data structure, but the block takes two arguments |key,value|. This
means
you could iterate through the values and when you find one for which you
want to know the associated key, you’ll have it right there:

key_for_value = nil
some_hash.each_pair do |letter,number|
key_for_value = letter if number == 2
end

If you’re doing this sort of thing a lot, you may want to consider a
different data structure. It’s not efficient to keep inverting the keys
and
values or to iterate through the entire hash search for a particular
pair.

-Jake

2010/2/11 John B. [email protected]:

I cant seem to figure this out, if i have a hash value can i then get
the key thats associated to that value.

So the hash.has_value(val)? method will return true or false if that
value exists in the hash but what i need to know is what is the key for
the particular value.

Any ideas?

Hash#rassoc

irb(main):001:0> {:foo=>:bar}.rassoc :bar
=> [:foo, :bar]
irb(main):002:0> {:foo=>:bar}.rassoc :foo
=> nil
irb(main):003:0>

You can do

key, = hash.rassoc your_value
Note, the comma is important.

Kind regards

robert

Thanks,