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.
There are many ways to remove a key from a hash and get the remaining hash in Ruby.
.slice
=> It will return selected keys and not delete them from the original hash.delete
=> It will delete the selected keys from the original hash(it can accept only one key and not more than one).except
=> It will return the remaining keys but not delete anything from the original hash.delete_if
=> In case you need to remove a key based on a value. It will obviously remove the matching keys from the original hashResults based on Ruby 2.2.2.