Ruby value of a hash key?

后端 未结 6 2154
暖寄归人
暖寄归人 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:45

    As an addition to e.g. @Intrepidd s answer, in certain situations you want to use fetch instead of []. For fetch not to throw an exception when the key is not found, pass it a default value.

    puts "ok" if hash.fetch('key', nil) == 'X'
    

    Reference: https://docs.ruby-lang.org/en/2.3.0/Hash.html .

提交回复
热议问题