To add a new pair to Hash I do:
{:a => 1, :b => 2}.merge!({:c => 3}) #=> {:a => 1, :b => 2, :c => 3}
Is there a similar way to delete a key from Hash ?
This works:
{:a => 1, :b => 2}.reject! { |k| k == :a } #=> {:b => 2}
but I would expect to have something like:
{:a => 1, :b => 2}.delete!(:a) #=> {:b => 2}
It is important that the returning value will be the remaining hash, so I could do things like:
foo(my_hash.reject! { |k| k == my_key })
in one line.
Instead of monkey patching or needlessly including large libraries, you can use refinements if you are using Ruby 2:
You can use this feature without affecting other parts of your program, or having to include large external libraries.
See Ruby on Rails: Delete multiple hash keys
in pure Ruby:
This is a one line way to do it, but it's not very readable. Recommend using two lines instead.
Oneliner plain ruby, it works only with ruby > 1.9.x:
Tap method always return the object on which is invoked...
Otherwise if you have required
active_support/core_ext/hash
(which is automatically required in every Rails application) you can use one of the following methods depending on your needs:except uses a blacklist approach, so it removes all the keys listed as args, while slice uses a whitelist approach, so it removes all keys that aren't listed as arguments. There also exist the bang version of those method (
except!
andslice!
) which modify the given hash but their return value is different both of them return an hash. It represents the removed keys forslice!
and the keys that are kept for theexcept!
:I've set this up so that .remove returns a copy of the hash with the keys removed, while remove! modifies the hash itself. This is in keeping with ruby conventions. eg, from the console