从数组

时间:2016-09-16 11:41:18

标签: ruby-on-rails ruby ruby-on-rails-4 hash

我有一个简单的数组

arr = ["Japan", "Egypt", "Spain", "Brazil",....]

我想提取每个元素并使其成为哈希

japan = Hash.new("Japan")

egypt = Hash.new("Egypt")

brazil = Hash.new("Brazil")

最终将所有哈希存储在一个灌篮哈希

country = {"Japan" => 0, "Egypt" => 0,"Brazil" => 0,.....}

5 个答案:

答案 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变量应为小写,如japanegypt,常量应为大写,如JAPANEGYPT

答案 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