2010-08-03 51 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