Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non destructive way of deleting a key from a hash

Is there a non-destructive way of deleting a key value pair from a hash?

For example, if you did

original_hash = {:foo => :bar}
new_hash = original_hash
new_hash = new_hash.reject{|key, _| key == :foo}

or

original_hash = {:foo => :bar}
new_hash = original_hash
new_hash = new_hash.dup
new_hash.delete(:foo)

then original_hash is unchanged, and new_hash is changed, but they're a tad verbose. However, if you did

original_hash = {:foo => :bar}
new_hash = original_hash
new_hash.delete(:foo)

then original_hash is changed, which isn't what I want.

Is there a single method that does what I want?

like image 682
Andrew Grimm Avatar asked Nov 21 '12 02:11

Andrew Grimm


1 Answers

Yes, you want reject:

new_hash = original_hash.reject{|key, _| key == :foo}
like image 61
pguardiario Avatar answered Sep 22 '22 16:09

pguardiario