Find has key from a value

J

John Butler

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
 
J

Jacob Mitchell

[Note: parts of this message were removed to make it a legal post.]
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
 
R

Robert Klemme

2010/2/11 John Butler said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,185
Messages
2,570,992
Members
47,586
Latest member
DLWKathie7

Latest Threads

Top