Simple hash print key?

I want to print the key for this hash key, but I cannot 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 another way?

+4
source share
3 answers

I do not quite understand. If you already know that you want puts value "a" , you only need to puts "a" .

It would be wise to look for a key to a given value, for example:

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

Or, if it is not known 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" 
+5
source

To get all the keys for the hash, use keys :

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

I know this is an old question, but I think that the original seeker intended to find the key when he does NOT know what it is; For example, when iterating through a hash.

A few other ways to get your hash key:

Given a hash definition:

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

The reason your first attempt failed:

 #.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 capture the key when repeating through a 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 are just in one ship and you want:

Get the key for this key (not sure why, since you already know the key):

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

Get the key for the given value:

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

All Articles