仅当 Ruby 散列中存在时才修改值

Modify a value in a Ruby hash only if present

我需要修改特定键的散列值,但如果该键不存在我不想添加,长版本为:

if my_hash.has_key?( :key )
    my_hash[ :key ] = true if my_hash[ :key ] == 0
    my_hash[ :key ] = false if my_hash[ :key ] == 1
    # leave value alone if it is not 0 or 1
else
    # leave hash alone if key is not present
end

不知道有没有更优雅的解决方案

也许用case声明

case my_hash[:key]                                                                                                                                                                   
when 0; my_hash[:key] = true                                                                                                                                                         
when 1; my_hash[:key] = false                                                                                                                                                        
end

出于好奇:)

[0,1].include?(my_hash[:key]) && my_hash[:key] = my_hash[:key].zero? 

一种方法可能是使用 "mapped" 值的散列,然后遍历普通散列并为其设置值

value_map = { 0 => true, 1 => false }
my_hash.each { |k, v| my_hash[k] = value_map.include?(v) ? value_map[v] : v }