我有一个Ruby哈希值的列表.有没有办法检查密钥的值,如果它等于"X",那么做"Y"?
我可以测试哈希是否有密钥使用hash.has_key?
,但现在我需要知道if hash.key == "X" then...
?
Mir*_*lus 56
使用方括号([])对哈希进行索引.就像数组一样.但是,不是使用数字索引进行索引,而是使用您用于键的字符串文字或符号来对哈希进行索引.所以如果你的哈希类似于
hash = { "key1" => "value1", "key2" => "value2" }
Run Code Online (Sandbox Code Playgroud)
你可以用它访问该值
hash["key1"]
Run Code Online (Sandbox Code Playgroud)
或者
hash = { :key1 => "value1", :key2 => "value2"}
Run Code Online (Sandbox Code Playgroud)
或者Ruby 1.9支持的新格式
hash = { key1: "value1", key2: "value2" }
Run Code Online (Sandbox Code Playgroud)
你可以用它访问该值
hash[:key1]
Run Code Online (Sandbox Code Playgroud)
nol*_*ith 13
这个问题似乎含糊不清.
我会尝试解释我的请求.
def do_something(data)
puts "Found! #{data}"
end
a = { 'x' => 'test', 'y' => 'foo', 'z' => 'bar' }
a.each { |key,value| do_something(value) if key == 'x' }
Run Code Online (Sandbox Code Playgroud)
这将循环遍历所有键值对,并仅在键为"x"时执行某些操作.
作为@Intrepidd答案的补充,在某些情况下你想用fetch
而不是[]
.为了fetch
在未找到密钥时不抛出异常,请将其传递给默认值.
puts "ok" if hash.fetch('key', nil) == 'X'
Run Code Online (Sandbox Code Playgroud)
参考:https://docs.ruby-lang.org/en/2.3.0/Hash.html.
这个怎么样?
puts "ok" if hash_variable["key"] == "X"
Run Code Online (Sandbox Code Playgroud)
您可以使用 [] 运算符访问哈希值
归档时间: |
|
查看次数: |
106510 次 |
最近记录: |