我有一段代码,下面这一行:
user.attributes.except('created_at', 'created_by', 'updated_at', 'updated_by', 'id')工作(返回哈希,并将键作为参数从其中删除),而将其更改为:
user.attributes.except(:created_at, :created_by, :updated_at, :updated_by, :id)不会(返回的散列仍然包含所有键)。这怎麽可能?
发布于 2012-08-16 16:18:10
因为attributes返回的哈希键是字符串,而不是符号。
http://apidock.com/rails/ActiveRecord/Base/attributes
正如其他人所说,字符串!=符号。
puts :a == 'a'
# => false发布于 2012-08-16 16:18:30
这是因为user.attributes中的键是字符串。您可以使用symbolize_keys方法对它们进行符号化,然后对符号使用except,如下所示。
user.attributes.symbolize_keys.except(:created_at, :created_by, :updated_at, :updated_by, :id)发布于 2018-02-14 16:31:03
我不希望在某些情况下(例如处理http json响应)出现这种行为。
所以我添加了一些改进。
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)
# => {}※附加信息
在写完上面的内容后,我找到了其他方法。
使用Hash#deep_symbolize_keys将所有键转换为符号!
{"a" => "hoge"}.deep_symbolize_keys!.except(:a) # => {}使用ActiveSupport::HashWithIndifferentAccess
{"a" => "hoge"}.with_indifferent_access.except(:a) # => {}谢谢
https://stackoverflow.com/questions/11983092
复制相似问题