哈希的简单打印键?

时间:2010-08-03 04:06:37

标签: ruby hash

我想从给定的哈希键中打印一个键,但我找不到一个简单的解决方案:

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

还有其他办法吗?

3 个答案:

答案 0 :(得分:14)

要从哈希中获取所有密钥,请使用keys方法:

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

答案 1 :(得分:10)

我知道这是一个较老的问题,但我认为最初的提问者想要的是找到钥匙,因为他不知道它是什么;例如,在遍历哈希时。

获取哈希密钥的其他几种方法:

给定哈希定义:

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

你第一次尝试的原因不起作用:

#.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)

所以如果你想在迭代哈希时抓住密钥:

#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!

如果你只是进入单行并希望:

获取给定密钥的密钥(不知道为什么,因为您已经知道密钥):

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

获取给定值的密钥:

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

答案 2 :(得分:6)

我不太明白。如果您已经知道puts值为"a",那么您只需要puts "a"

有意义的是搜索给定值的键,如下所示:

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

或者,如果不知道密钥是否存在于哈希中,并且您希望仅在它存在时才打印它:

puts "a" if myhash.has_key? "a"
相关问题