Reputation: 2074
How do I make this:
["ford|white", "honda|blue"]
Into this:
[{'make'=>'ford', 'color'=>'white'}, {'make'=>'honda', 'color'=>'blue'}]
Upvotes: 1
Views: 310
Reputation: 34176
input = ["ford|white", "honda|blue"]
input.map do |car|
Hash[ %w(make color).zip car.split('|') ]
end
=> [{"make"=>"ford", "color"=>"white"}, {"make"=>"honda", "color"=>"blue"}]
Upvotes: 2
Reputation: 1
This should do it
yourarray = ["ford|white", "honda|blue"]
yourhash = yourarray.map {|x| y = x.split('|'); {"make" => y[0], "color" => y[1]}}
Upvotes: 0
Reputation: 3509
["ford|white", "honda|blue"].collect do |str|
ary = str.split('|')
{ 'make' => ary[0], 'color' => ary[1] }
end
gives me
[{"color"=>"white", "make"=>"ford"}, {"color"=>"blue", "make"=>"honda"}]
Upvotes: 2
Reputation: 160191
Without thought:
> l = ["ford|white", "honda|blue"]
> m = l.collect { |m| make, color = m.split('|'); { make: make, color: color } }
=> [{:make=>"ford", :color=>"white"}, {:make=>"honda", :color=>"blue"}]
(Using symbols for keys, generally recommended, IMO.)
Upvotes: 2