Ruby数组用params哈希

Del*_*ang 0 ruby json

我有一个数组:

 arr = ["dog", "cat", "eel"]
Run Code Online (Sandbox Code Playgroud)

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

'{"dog": {}, "cat": {}, "eel": {} }'
Run Code Online (Sandbox Code Playgroud)

并不是:

'{"dog"=> {}, "cat"=> {}, "eel"=> {} }'
Run Code Online (Sandbox Code Playgroud)

我尝试过使用:

res = arr.each_with_object({}) { |k,h| h[k] = {} }
Run Code Online (Sandbox Code Playgroud)

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

Aru*_*hit 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":{}}
Run Code Online (Sandbox Code Playgroud)