有一种方法可以投射:
Hash
HashWithIndifferentAccess
ActionController:Parameters
到Hash
?
我有一个序列化属性,看起来所有3种类型都在数据库表中。
答案 0 :(得分:1)
您可以使用:
hash_like_object.to_h
使用Array of arrays
,Hash
,HashWithIndifferentAccess
和ActionController::Parameters
进行测试:
array = [[:a,1],[:b,2]]
hash = {a: 1, b: 2}
hash2 = HashWithIndifferentAccess.new(a: 1, b: 2)
parameters = ActionController::Parameters.new(a: 1, b: 2)
[array, hash, hash2, parameters].each do |hash_like_object|
h = hash_like_object.to_h
puts "%s (%s) -> %s (%s)" % [hash_like_object, hash_like_object.class, h, h.class]
end
# [[:a, 1], [:b, 2]] (Array) -> {:a=>1, :b=>2} (Hash)
# {:a=>1, :b=>2} (Hash) -> {:a=>1, :b=>2} (Hash)
# {"a"=>1, "b"=>2} (ActiveSupport::HashWithIndifferentAccess) -> {"a"=>1, "b"=>2} (Hash)
# {"a"=>1, "b"=>2} (ActionController::Parameters) -> {"a"=>1, "b"=>2} (Hash)