Tutorial :Simple printing key of a hash? [closed]


I want to print a key from a given hash key but I can't find a 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  

Is there any other way?


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"  


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

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


I know this is an older question, but I think what the original asker was intending was to find the key when he DOESN'T know what it is; For instance, when iterating through the hash.

A couple of other ways to get your hash key:

Given the hash definition:

myhash = Hash.new  myhash["a"] = "Hello, "  myhash["b"] = "World!"  

The reason your first try didn't work:

#.fetch just returns the value at the given key UNLESS the key doesn't exist  #only then does the optional code block run.  myhash.fetch("a"){|k|  puts k }   #=> "Hello!" (this is a returned value, NOT a screen output)  myhash.fetch("z"){|k|  puts k }   #z  (this is a printed screen output from the puts command)  #=>nil   (this is the returned value)  

So if you want to grab the key when iterating through the hash:

#when pulling each THEN the code block is always run on each result.  myhash.each_pair {|key,value| puts "#{key} = #{value}"}  #a = Hello,   #b = World!  

And if you're just into one-liners and want to:

Get the key for a given key (not sure why since you already know the key):

myhash.each_key {|k| puts k if k == "a"}  #a  

Get the key(s) for a given value:

myhash.each_pair {|k,v| puts k if v == "Hello, "}   #a  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »