【发布时间】:2015-08-10 01:18:27
【问题描述】:
我有一个 ruby 哈希,看起来像:
{ id: 123, name: "test" }
我想把它转换成:
{ "id" => 123, "name" => "test" }
【问题讨论】:
我有一个 ruby 哈希,看起来像:
{ id: 123, name: "test" }
我想把它转换成:
{ "id" => 123, "name" => "test" }
【问题讨论】:
如果您使用的是 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" }
【讨论】:
我喜欢each_with_object 在这种情况下:
hash = { id: 123, name: "test" }
hash.each_with_object({}) { |(key, value), h| h[key.to_s] = value }
#=> { "id" => 123, "name" => "test" }
【讨论】:
在纯 Ruby(没有 Rails)中,您可以结合使用 Enumerable#map 和 Array#to_h:
hash = { id: 123, name: "test" }
hash.map{|key, v| [key.to_s, v] }.to_h
【讨论】:
h = { id: 123, name: "test" }
假设你想改变h:
h.keys.each { |k| h[k.to_s] = h.delete(k) }
h #=> {"id"=>123, "name"=>"test"}
【讨论】: