如何将数组映射到散列

时间:2017-05-10 23:25:28

标签: ruby-on-rails ruby

我想将任意Ruby数组映射到Hash。

输入:

['bar1', 'bar2', 'bar3']

(数组将包含0到3个元素。)

输出:

{ foo1: 'bar1', foo2: 'bar2', foo3: 'bar3' }

我正在寻找最优雅的解决方案。

1 个答案:

答案 0 :(得分:2)

使用#zip

  

foo.zip(巴).to_h

irb(main):003:0> [:foo1, :foo2, :foo3].zip(['bar1', 'bar2', 'bar3']).to_h
=> {:foo1=>"bar1", :foo2=>"bar2", :foo3=>"bar3"}
irb(main):004:0> b=['bar1', 'bar2', 'bar3']
=> ["bar1", "bar2", "bar3"]
irb(main):005:0> f=[:foo1, :foo2, :foo3]
=> [:foo1, :foo2, :foo3]
irb(main):006:0> f.zip(b).to_h
=> {:foo1=>"bar1", :foo2=>"bar2", :foo3=>"bar3"}
irb(main):007:0> f.zip(b[0..2]).to_h
=> {:foo1=>"bar1", :foo2=>"bar2", :foo3=>"bar3"}
irb(main):009:0> f.zip(b[0..1]).to_h
=> {:foo1=>"bar1", :foo2=>"bar2", :foo3=>nil}
irb(main):010:0> f.zip(b[0..0]).to_h
=> {:foo1=>"bar1", :foo2=>nil, :foo3=>nil}
irb(main):011:0> f.zip([]).to_h
=> {:foo1=>nil, :foo2=>nil, :foo3=>nil}