2010-08-03 54 views
4

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

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 

有没有其他办法?

+0

很不清楚。也许'my_hash.each {| k,v |把k}'? – 2010-08-03 06:13:09

回答

5

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

又有什么意义。将搜索给定值的关键,就像这样:

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

或者,如果它是未知的哈希是否存在与否的关键,而要打印它只是如果它存在:

puts "a" if myhash.has_key? "a" 
+0

嗯......你的第一段答案确实有意义...... tnx – mhd 2010-08-05 04:52:16

12

要获得所有从哈希键使用keys方法:

{ "1" => "foo", "2" => "bar" }.keys 
=> ["1", "2"] 
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 

拿到钥匙(s)给定值:

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