2016-12-02 150 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:感謝您的評論。我更新了答案。 –