如何转换Ruby哈希以使其所有键都是字符串

时间:2015-05-27 19:12:41

标签: ruby hash stringify

我有一个ruby哈希,看起来像:

{ id: 123, name: "test" }

我想将其转换为:

{ "id" => 123, "name" => "test" }

4 个答案:

答案 0 :(得分:4)

在这种情况下,我喜欢each_with_object

hash = { id: 123, name: "test" }
hash.each_with_object({}) { |(key, value), h| h[key.to_s] = value }
#=> { "id" => 123, "name" => "test" }

答案 1 :(得分:3)

如果您使用的是Rails或ActiveSupport:

hash = { id: 123, description: "desc" }
hash.stringify #=> { "id" => 123, "name" => "test" }

如果你不是:

hash = { id: 123, name: "test" }
Hash[hash.map { |key, value| [key.to_s, value] }] #=> { "id" => 123, "name" => "test" }

答案 2 :(得分:1)

在纯Ruby(没有Rails)中,您可以使用Enumerable#mapArray#to_h的组合执行此操作:

hash = { id: 123, name: "test" }
hash.map{|key, v| [key.to_s, v] }.to_h

答案 3 :(得分:0)

h = { id: 123, name: "test" }

假设您要改变h

h.keys.each { |k| h[k.to_s] = h.delete(k) }
h #=> {"id"=>123, "name"=>"test"}