Rails' `Hash#except`
A cool feature provided by Rails is the #except
method on Hash
. This function removes a key-value pair from a hash.
Let's remove a Rails parameter, the most obvious use case I can think of:
[1] pry(#<SessionsController>)> params
=> {"utf8"=>"✓",
"user_login"=>{"email"=>"", "password"=>"general"},
"controller"=>"sessions",
"action"=>"create"}
[2] pry(#<SessionsController>)> params.except(:utf8)
=> {"user_login"=>{"email"=>"", "password"=>"general"},
"controller"=>"sessions",
"action"=>"create"}
And the source code:
[1] pry(#<SessionsController>)> show-source Hash#except
From: /Users/dev/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.7.1/lib/active_support/core_ext/hash/except.rb @ line 9:
Owner: Hash
Visibility: public
Number of lines: 3
def except(*keys)
dup.except!(*keys)
end
[2] pry(#<SessionsController>)> show-source Hash#except!
From: /Users/dev/.rvm/gems/ruby-2.2.5/gems/activesupport-4.2.7.1/lib/active_support/core_ext/hash/except.rb @ line 17:
Owner: Hash
Visibility: public
Number of lines: 4
def except!(*keys)
keys.each { |key| delete(key) }
self
end
Thanks Rails!
Tweet