我该怎么做:
["ford|white", "honda|blue"]
进入这个:
[{'make'=>'ford', 'color'=>'white'}, {'make'=>'honda', 'color'=>'blue'}]
我该怎么做:
["ford|white", "honda|blue"]
进入这个:
[{'make'=>'ford', 'color'=>'white'}, {'make'=>'honda', 'color'=>'blue'}]
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"}]
不假思索:
> 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 的键符号。)
["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"}]
这应该这样做
yourarray = ["ford|white", "honda|blue"]
yourhash = yourarray.map {|x| y = x.split('|'); {"make" => y[0], "color" => y[1]}}