Our daily Method #4: Hash#excluding en Hash#only
Geplaatst door Remco van 't Veer vr, 08 feb 2008 08:00:00 GMT
This will look familiar:
u = params[:user]
attr = if u[:password].blank?
u.reject do |k,_|
[:password, :password_confirmation].include?(k)
end
end
User.update_attributes(attr || u)
But it smells like something reusable. I would like to write:
u = params[:user]
attr = if u[:password].blank?
u.excluding(:password, :password_confirmation)
end
User.update_attributes(attr || u)
Easily to implement, including its little brother only
, with:
class Hash
def excluding(*keys)
reject{|k,_| keys.include?(k)}
end
def only(*keys)
reject{|k,_| !keys.include?(k)}
end
end
Disclaimer: the above example doesn’t really work in Rails because params
is a hash with indifferent access. Making an indifferent variant is up you! :)
In rails, only already exists, and you can use except instead of excluding.
I can’t believe I missed
Hash#except
. But I can not find Rails’sHash#only
variant. I did find out Merb has aHash#only
method.