Ruby-从数组到数组的数组中收集相同的数字

问题描述:

我创建了一个非常丑陋的脚本来从数组中收集相同的数字.我认为这不是一种非常Ruby的方法:)任何人都可以提供更干净的解决方案吗?

I have created a very ugly script to collect same numbers from an array. I don't think this is a very Ruby way :) Anyone could provide a more clean solution?

ar = [5, 5, 2, 2, 2, 6, 6]

collections = []
collect_same = []

while ar.length > 0
 first = ar.values_at(0).join.to_i 
 second = ar.values_at(1).join.to_i 
  if ar.length == 1 
   collect_same << ar[0]
   collections << collect_same
   break
  else  
   sum = ar.values_at(0, 1).inject {|a,b| a + b}
   if second == first 
    p collect_same << ar[0]
    ar.shift 
   else 
    collect_same << ar[0]
    collections << collect_same
    collect_same = []
    ar.shift 
   end 
  end 
end 

p collections 

输出:

=> [[5, 5], [2, 2, 2], [6, 6]]

请注意,在主数组中,相同的数字总是一个接一个.所以我不会有像这样的主数组- ar = [1、2、1、2]

Note, that in primary array same numbers always goes one after another. So I wouldn't have primary array like this - ar = [1, 2, 1, 2]

使用 chunk_while :

[5, 5, 2, 2, 2, 6, 6].chunk_while(&:==).to_a
#=> [[5, 5], [2, 2, 2], [6, 6]]

2.3之前的Ruby:

Ruby prior to 2.3:

[5, 5, 2, 2, 2, 6, 6].each_with_object([]) do |e, acc|
  acc.last && acc.last.last == e ? acc.last << e : acc << [e]
end
#=> [[5, 5], [2, 2, 2], [6, 6]]