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
putsthe value"a", then you only need toputs "a".What would make sense would be to search for the key of a given value, like so:
Or, if it’s unknown whether the key exists in the hash or not, and you want to print it only if it exists: