我想从给定的哈希键打印一个键,但我找不到一个简单的解决方案:
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
Run Code Online (Sandbox Code Playgroud)
还有其他方法吗?
Rya*_*igg 14
要从哈希中获取所有密钥,请使用keys方法:
{ "1" => "foo", "2" => "bar" }.keys
=> ["1", "2"]
Run Code Online (Sandbox Code Playgroud)
小智 10
我知道这是一个较老的问题,但我认为最初的提问者想要的是在他不知道它是什么时找到钥匙; 例如,在迭代哈希时.
获取哈希键的其他几种方法:
给定哈希定义:
myhash = Hash.new
myhash["a"] = "Hello, "
myhash["b"] = "World!"
Run Code Online (Sandbox Code Playgroud)
你第一次尝试不起作用的原因:
#.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)
Run Code Online (Sandbox Code Playgroud)
因此,如果您想在迭代哈希时获取密钥:
#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!
Run Code Online (Sandbox Code Playgroud)
如果你只是进入单行并希望:
获取给定密钥的密钥(不知道为什么,因为您已经知道密钥):
myhash.each_key {|k| puts k if k == "a"}
#a
Run Code Online (Sandbox Code Playgroud)
获取给定值的密钥:
myhash.each_pair {|k,v| puts k if v == "Hello, "}
#a
Run Code Online (Sandbox Code Playgroud)
我不太明白.如果你已经知道你想要puts的价值"a",那么你只需要puts "a".
有意义的是搜索给定值的键,如下所示:
puts myhash.key 'bar'
=> "a"
Run Code Online (Sandbox Code Playgroud)
或者,如果未知密钥是否存在于哈希中,并且您希望仅在它存在时才打印它:
puts "a" if myhash.has_key? "a"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32986 次 |
| 最近记录: |