我该怎么做:
["ford|white", "honda|blue"]
进入这个:
[{'make'=>'ford', 'color'=>'white'}, {'make'=>'honda', 'color'=>'blue'}]
答案 0 :(得分: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。)
答案 1 :(得分: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"}]
答案 2 :(得分: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"}]
答案 3 :(得分:0)
这应该这样做
yourarray = ["ford|white", "honda|blue"]
yourhash = yourarray.map {|x| y = x.split('|'); {"make" => y[0], "color" => y[1]}}