1

How do I make this:

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

Into this:

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

4 Answers 4

2
["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"}] 
Sign up to request clarification or add additional context in comments.

Comments

2

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.)

Comments

2
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"}]

Comments

0

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]}­}

1 Comment

the solution above is perhaps prettier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.