1

我该怎么做:

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

进入这个:

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

4 回答 4

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"}]
于 2012-08-01T23:01:57.127 回答
2

不假思索:

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

(通常建议使用 IMO 的键符号。)

于 2012-08-01T22:54:26.733 回答
2
["ford|white", "honda|blue"].collect do |str|
  ary = str.split('|')
  { 'make' => ary[0], 'color' => ary[1] }
end

给我

[{"color"=>"white", "make"=>"ford"}, {"color"=>"blue", "make"=>"honda"}] 
于 2012-08-01T22:54:36.307 回答
0

这应该这样做

yourarray = ["ford|white", "honda|blue"]
yourhash = yourarray.map­ {|x| y = x.spl­it('|'); {"mak­e" => y[0],­ "colo­r" => y[1]}­}
于 2012-08-01T23:00:10.497 回答