2016-12-02 108 views
1

有投单的方式:一个HashRails将类似散列的对象转换为散列?

  • Hash
  • HashWithIndifferentAccess
  • ActionController:Parameters

我有一个序列化的属性,它看起来像所有3种类型都在数据库表中。

+0

'to_h'将工作这些 –

+0

'所有这些to_h'作品? –

+0

是的,看我的答案。我现在正在添加示例。 –

回答

1

您可以使用:

hash_like_object.to_h 

测试与Array of arraysHashHashWithIndifferentAccessActionController::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) 
+0

只需使用'to_h'(不含to_a)即可用于'HashWithIndifferentAccess',但尚未针对'ActionController:Parameters'进行测试。 – archana

+0

这是最好的答案 –

+0

@archana:感谢您的评论。我更新了答案。 –