我的哈希:
hash={value1: "2",value2: "1",value3: "6",value4: "2" }
我想要的是删除所有值为“2”的键值对,如下所示:
hash={value2: "1",value3: "6"}
怎么做?
这是如何使用的delete_if
?
hash={value1: "2",value2: "1",value3: "6",value4: "2" }
hash.delete_if{|_,v| v == "2"}
# => {:value2=>"1", :value3=>"6"}
hash
# => {:value2=>"1", :value3=>"6"}
如果您不想修改原始文件,hash
那么您也可以使用Hash#reject
:
hash={value1: "2",value2: "1",value3: "6",value4: "2" }
new_hash=hash.reject{|_,v| v == "2"}
# => {:value2=>"1", :value3=>"6"}
hash # => {:value1=>"2", :value2=>"1", :value3=>"6", :value4=>"2"}