Ruby - 将具有管道分隔值的数组转换为散列数组

时间:2012-08-01 22:40:36

标签: ruby

我该怎么做:

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

进入这个:

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

4 个答案:

答案 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.spl­it('|'); {"mak­e" => y[0],­ "colo­r" => y[1]}­}