将两个数组组合成一个哈希

时间:2012-10-02 17:22:11

标签: ruby arrays hash

我正在尝试将两个数组合并为一个哈希值。

@sample_array = ["one", "Two", "Three"]
@timesheet_id_array = ["96", "97", "98"]

我想将结果输出到名为@hash_array的哈希中。有没有一种简单的方法可以将两者组合在一个代码块中,这样如果你在最后调用puts,它在控制台中看起来像这样

{"one" => "96", "Two" => "97", "Three" => "98"}

我认为这可以用一行或两行代码完成。

5 个答案:

答案 0 :(得分:36)

试试这个

keys = [1, 2, 3]
values = ['a', 'b', 'c']
Hash[keys.zip(values)]

感谢

答案 1 :(得分:7)

@hash_array = {}
@sample_array.each_with_index do |value, index|
  @hash_array[value] = @timesheet_id_array[index]
end

答案 2 :(得分:2)

看起来最美的爱莫人

[:a,:b,:c].zip([1,2,3]).to_h

# {:a=>1, :b=>2, :c=>3}

答案 3 :(得分:1)

博士。 Nic建议在http://drnicwilliams.com/2006/10/03/zip-vs-transpose/

解释好两个选项

答案 4 :(得分:0)

@hash_array = {}
0.upto(@sample_array.length - 1) do |index|
  @hash_array[@sample_array[index]] = @timesheet_id_array[index]
end
puts @hash_array.inspect