Hash.except () does not work with character keys

I have a piece of code in which this line:

user.attributes.except('created_at', 'created_by', 'updated_at', 'updated_by', 'id') 

works (returns a hash with keys passed as arguments removed from it), and when changed:

 user.attributes.except(:created_at, :created_by, :updated_at, :updated_by, :id) 

no (the returned hash still contains all the keys). How is this possible?

+4
source share
3 answers

Because attributes return a hash with keys as a string, not a character.

http://apidock.com/rails/ActiveRecord/Base/attributes

and, as others say, String! = Symbol.

 puts :a == 'a' # => false 
+7
source

This is because the keys in user.attributes are strings. You can symbolize them using the symbolize_keys method, and then use except with such characters.

 user.attributes.symbolize_keys.except(:created_at, :created_by, :updated_at, :updated_by, :id) 
+6
source

I do not hope this behavior in some cases (e.g. handling http json response)

So, I have added clarifications.

 module HashUtil refine Hash do def eager_except(*args) proc = Proc.new do |key| case when key.is_a?(Symbol) key.to_s when key.is_a?(String) key.to_sym else nil end end eager_args = (args + args.map(&proc)).compact except(*eager_args) end end end using HashUtil hash = { a: 'a', "b" => 'b' } hash.eager_except('a', :b) # => {} 

※ Additional Information

after writing above, I found other ways.

convert all keys to characters using Hash # deep_symbolize_keys!

 {"a" => "hoge"}.deep_symbolize_keys!.except(:a) # => {} 

use ActiveSupport :: HashWithIndifferentAccess

 {"a" => "hoge"}.with_indifferent_access.except(:a) # => {} 

thanks

0
source

All Articles