反转阵列的最佳方式?

Jer*_*ith 1 ruby

如果我有像这样的数组

ary = [0, 0, 3, 0, 0, 0, 2, 0, 1, 0, 1, 1, 0] 
Run Code Online (Sandbox Code Playgroud)

获取阵列中有多少索引的列表的最高性能是什么?

inverted = [2,2,2,6,6,8,10,11] 
Run Code Online (Sandbox Code Playgroud)

这就是我想出来的,但似乎有一种更有效的方式:

a = []
ary.each_with_index{|v,i| a << Array.new(v, i) if v != 0}
a.flatten
 => [2, 2, 2, 6, 6, 8, 10, 11] 
Run Code Online (Sandbox Code Playgroud)

tok*_*and 5

除非剖析证明这是一个瓶颈,否则清洁工是一种功能性方法:

>> ary.each_with_index.map { |x, idx| [idx]*x }.flatten(1)
=> [2, 2, 2, 6, 6, 8, 10, 11]
Run Code Online (Sandbox Code Playgroud)

如果您使用Ruby 1.9,我建议这样做(感谢sawa指出Enumerable#flat_map):

>> ary.flat_map.with_index { |x, idx| [idx]*x }
=> [2, 2, 2, 6, 6, 8, 10, 11]
Run Code Online (Sandbox Code Playgroud)

[编辑:删除示例使用injecteach_with_object,它们不太可能比flat_map+ 更快with_index]