我有一个简单的数组
arr = ["Japan", "Egypt", "Spain", "Brazil",....]
我想提取每个元素并使其成为哈希
japan = Hash.new("Japan")
egypt = Hash.new("Egypt")
brazil = Hash.new("Brazil")
最终将所有哈希存储在一个灌篮哈希
中country = {"Japan" => 0, "Egypt" => 0,"Brazil" => 0,.....}
答案 0 :(得分:2)
试试这个。
country = {}
arr.each do |name|
country[name] = 0
end
答案 1 :(得分:0)
我不确定您想要做什么,但您可以尝试以下方法:
arr = ["Japan", "Egypt", "Spain", "Brazil"]
arr.each { |a| Object.const_set(a, Hash.new(a)) } #initialize hashes
Country = arr.map {|a| [a, 0]}.to_h
#=> {"Japan"=>0, "Egypt"=>0, "Spain"=>0, "Brazil"=>0}
或
Country = Hash[arr.map {|a| [a, 0]}]
#=> {"Japan"=>0, "Egypt"=>0, "Spain"=>0, "Brazil"=>0}
注意:Ruby变量应为小写,如japan
和egypt
,常量应为大写,如JAPAN
和EGYPT
。
答案 2 :(得分:0)
要获得您指定为请求输出的结果:
countries = ["Japan", "Egypt", "Spain", "Brazil"]
countries_hash = countries.zip([0] * countries.size).to_h
#⇒ {"Japan"=>0, "Egypt"=>0, "Spain"=>0, "Brazil"=>0}
答案 3 :(得分:0)
我认为reduce
会有所帮助:
arr = ["Japan", "Egypt", "Spain", "Brazil",....]
arr.reduce({}) do |hash, element|
hash[element] = 0
hash
end
答案 4 :(得分:0)
最明显的:
countries.map { |country| [country, 0] }.to_h