ruby-on-railsruby

Delete multiple hash keys


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?


Solution

  • I'm guessing you're unaware of the Hash#except method ActiveSupport adds to Hash.

    It would allow your code to be simplified to:

    redirect_to my_path(params.except(:controller, :action, :other_key))
    

    Also, you wouldn't have to monkey patch, since the Rails team did it for you!