Ruby on Rails: Delete multiple hash keys

Viewed 76371

I often find myself writing this:

params.delete(:controller)  
params.delete(:action)  
params.delete(:other_key)  
redirect_to my_path(params)  

The trail of deletes doesn't feel right and neither does:

[:controller, :action, :other_key].each do |k|
  params.delete(k)
end

Is there anything simpler and cleaner?

7 Answers

Starting from Ruby 3.0, Hash#except is supported directly. This means we would not need activesupport to access Hash#except.

From documentation:

Hash#except(*keys) → hash

This method returns a new hash, which includes everything from the original hash except the given keys.

example:

h = { a: 100, b: 200, c: 300, d: 400 }
h.except(:a, :d) #=> {:b=>200, :c=>300}

Reference:

https://docs.ruby-lang.org/en/3.0.0/Hash.html#method-i-except

Related