oprogfrogo
oprogfrogo

Reputation: 2074

Ruby - Convert Array with pipe delimited values to an array of hashes

How do I make this:

["ford|white", "honda|blue"]

Into this:

[{'make'=>'ford', 'color'=>'white'}, {'make'=>'honda', 'color'=>'blue'}]

Upvotes: 1

Views: 310

Answers (4)

AJcodez
AJcodez

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

Pablo Karlsson
Pablo Karlsson

Reputation: 1

This should do it

yourarray = ["ford|white", "honda|blue"]
yourhash = yourarray.map­ {|x| y = x.spl­it('|'); {"mak­e" => y[0],­ "colo­r" => y[1]}­}

Upvotes: 0

Rich Drummond
Rich Drummond

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

Dave Newton
Dave Newton

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

Related Questions