Rails将类似哈希的对象转换为哈希值?

时间:2016-12-02 21:26:42

标签: ruby-on-rails

有一种方法可以投射:

  • Hash
  • HashWithIndifferentAccess
  • ActionController:Parameters

Hash

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

1 个答案:

答案 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)