我正在寻找Ruby Core中与数组等效的String#split
,并惊讶地发现它并不存在。有没有比下面更好的方法来根据值将一个数组分成多个子数组?
class Array
def split( split_on=nil )
inject([[]]) do |a,v|
a.tap{
if block_given? ? yield(v) : v==split_on
a << []
else
a.last << v
end
}
end.tap{ |a| a.pop if a.last.empty? }
end
end
p (1..9 ).to_a.split{ |i| i%3==0 },
(1..10).to_a.split{ |i| i%3==0 }
#=> [[1, 2], [4, 5], [7, 8]]
#=> [[1, 2], [4, 5], [7, 8], [10]]
编辑:对于那些感兴趣的人来说,引发这个请求的“现实世界”问题可以在this answer中看到,我在这里使用了@fd的答案来实现。
https://stackoverflow.com/questions/4800337
复制相似问题