Ruby数组用params哈希

时间:2014-01-07 13:13:21

标签: ruby json

我有一个数组:

 arr = ["dog", "cat", "eel"]

我想把它转换成像这样的JSON:

'{"dog": {}, "cat": {}, "eel": {} }'

而不是:

'{"dog"=> {}, "cat"=> {}, "eel"=> {} }'

我尝试过使用:

res = arr.each_with_object({}) { |k,h| h[k] = {} }

我觉得我错过了一些非常明显的东西。有没有办法在回复时单引号?

1 个答案:

答案 0 :(得分:6)

请尝试以下代码:

require 'json'

arr = ["dog", "cat", "eel"]
puts Hash[arr.each_with_object({}).to_a].to_json
# >> {"dog":{},"cat":{},"eel":{}}
puts Hash[arr.map{|e| [e,{}]}].to_json # you can do this way also
# >> {"dog":{},"cat":{},"eel":{}}