问题描述
我有一个Ruby哈希值的列表。有没有办法来检查键的值,如果它等于X,然后做Y?
我可以测试,看看哈希是否有一个键使用 hash.has_key?
,但现在我需要知道如果hash.key ==X,那么... $ c $使用方括号([])对哈希进行索引。使用方括号([])对哈希进行索引。就像数组一样。但是使用数字索引进行索引,而不是使用您用于该键的字符串文字或符号对哈希进行索引。
所以如果你的哈希类似于
hash = {key1=> value1,key2=> value2}
您可以通过
hash [key1]
或for
hash = {:key1 => value1,:key2 => value2}
或Ruby 1.9支持的新格式
hash = {key1:value1,key2:value2}
你可以通过
hash [:key1]
I've got a list of values that are in a Ruby hash. Is there a way to check the value of the key and if it equals "X", then do "Y"?
I can test to see if the hash has a key using hash.has_key?
, but now I need to know if hash.key == "X" then...
?
Hashes are indexed using the square brackets ([]). Just as arrays. But instead of indexing with the numerical index, hashes are indexed using either the string literal you used for the key, or the symbol.So if your hash is similar to
hash = { "key1" => "value1", "key2" => "value2" }
you can access the value with
hash["key1"]
or for
hash = { :key1 => "value1", :key2 => "value2"}
or the new format supported in Ruby 1.9
hash = { key1: "value1", key2: "value2" }
you can access the value with
hash[:key1]
这篇关于散列键的Ruby值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!