有投单的方式:一个Hash
Rails将类似散列的对象转换为散列?
Hash
HashWithIndifferentAccess
ActionController:Parameters
?
我有一个序列化的属性,它看起来像所有3种类型都在数据库表中。
有投单的方式:一个Hash
Rails将类似散列的对象转换为散列?
Hash
HashWithIndifferentAccess
ActionController:Parameters
?
我有一个序列化的属性,它看起来像所有3种类型都在数据库表中。
您可以使用:
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)
只需使用'to_h'(不含to_a)即可用于'HashWithIndifferentAccess',但尚未针对'ActionController:Parameters'进行测试。 – archana
这是最好的答案 –
@archana:感谢您的评论。我更新了答案。 –
'to_h'将工作这些 –
'所有这些to_h'作品? –
是的,看我的答案。我现在正在添加示例。 –