Ruby value of a hash key?

后端 未结 6 2243
暖寄归人
暖寄归人 2021-01-31 08:43

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 ha

6条回答
  •  青春惊慌失措
    2021-01-31 08:58

    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]
    

提交回复
热议问题