Reputation:
My hash:
hash={value1: "2",value2: "1",value3: "6",value4: "2" }
What I want is to remove all key value pairs with value of "2" like this:
hash={value2: "1",value3: "6"}
How to do that?
Upvotes: 11
Views: 4239
Reputation: 118261
How is this using 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"}
If you don't want to modify the original hash
then you could use also 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"}
Upvotes: 14