-2

I want to map an arbitrary Ruby Array to a Hash.

Input:

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

(The array will have between zero and three elements.)

Output:

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

I'm looking for the most elegant solution.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Barry Fruitman
  • 12,316
  • 13
  • 72
  • 135
  • 2
    @coreyward Way to close this question without even comparing it to the other answer. My input is not an array of key-value pairs but whatever. – Barry Fruitman May 10 '17 at 23:44
  • 2
    Your question doesn't make sense. Where are `:foo1`, `:foo2` and `:foo3` supposed to come from? Is the code supposed to create a symbol for each element in the input array? Your question needs to state where they originate or why. – the Tin Man May 10 '17 at 23:49
  • 1
    @theTinMan I'd say that's obvious from the question. – Barry Fruitman May 10 '17 at 23:56
  • 2
    @BarryFruitman Hi Barry, I did consider that, but ultimately ruled that the community would not benefit from addressing this question again (there are over a dozen similar) simply to assist you in understanding. You're welcome to ask again, but first please use search, address how your needs are different, and share *what you have tried already*. – coreyward May 11 '17 at 15:11

1 Answers1

2

Use #zip.

foo.zip(bar).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}
Chloe
  • 25,162
  • 40
  • 190
  • 357