2

我有一个数组:

a = [[676, "/"], [679, "/", 680, "/"], [4, "3.7", "111.55", "/"], [668, "/"], [681, "/", 682, "/"]]

想要有这样的输出:

a = [[676], [679], [680], [4, "3.7", "111.55"], [668], [681], [682]]

尝试过这样的事情:

a.flatten.join(",").split("/")

这给出了这样的东西:

["676,", ",679,", ",680,", ",4,3.7,111.55,", ",668,", ",681,", ",682,"]
4

4 回答 4

4

这是您需要的:

a.flatten.chunk { |x| x != '/' }.select(&:first).map(&:last)  
#=> [[676], [679], [680], [4, "3.7", "111.55"], [668], [681], [682]]

或者:

a.flatten.chunk { |x| x != '/' }.map { |bool, arr| arr if bool }.compact
于 2012-08-10T06:44:58.340 回答
2

这有点乱(正如 smathy 所说的那样,这是一个令人讨厌的问题),并且可能不是很灵活地改变,但是:

 arr = [[676­, "/"],­ [679,­ "/", 680, "/"],­ [4, "3.7"­, "111.­55", "/"],­ [668,­ "/"],­ [681,­ "/", 682, "/"]]­
arr.i­nject([]) do |res,­ el|
  tmp = []
  el.ea­ch do |inne­r_el|
    if inner­_el == "/"
      res << tmp
      tmp = []
    else
      tmp << inner­_el
    end
  end
  res
end
于 2012-08-10T06:18:43.277 回答
1

原始数组似乎无关紧要,因此我们可以使用它flatten来简化inject

a.flatten
 .inject([[]]) { |m, e| e == '/' ? m.push([]) : m.last.push(e); m }
 .reject(&:empty?)

finalreject需要从 final 中删除杂散的空数组"/"

于 2012-08-10T06:35:57.113 回答
1

尝试使用

a.map!{|x| x.reject{|x| x=='/'}}

这将工作..

于 2012-08-10T06:55:36.567 回答