tags:

views:

50

answers:

2

Hi, I want to print a key from a given hash key
but can't find simple solution

myhash = Hash.new
myhash["a"] = "bar"

# not working
myhash.fetch("a"){|k|  puts k } 

# working, but ugly
if myhash.has_key("a")?
    puts "a"
end

Any other way?
tnx

+2  A: 

I don't quite understand. If you already know you want to puts the value "a", then you only need to puts "a".

What would make sense would be to search for the key of a given value, like so:

puts myhash.key 'bar'
=> "a"

Or, if it's unknown whether the key exists in the hash or not, and you want to print it only if it exists:

puts "a" if myhash.has_key? "a"
deceze
hmmm...your 1st paragraph answer does make sense...tnx
mhd
+1  A: 

To get all the keys from a hash use the keys method:

{ "1" => "foo", "2" => "bar" }.keys
=> ["1", "2"]
Ryan Bigg