2011-12-13 63 views

回答

9

在Ruby 1.8.7和1.9中,不带块的迭代器方法返回Enumerator对象。所以,你可以这样做:

[0, 0, 1, 0, 1].each_with_index.select { |num, index| num > 0 }.map { |pair| pair[1] } 
# => [2, 4] 

通过步进:

[0, 0, 1, 0, 1].each_with_index 
# => #<Enumerator: [0, 0, 1, 0, 1]:each_with_index> 
_.select { |num, index| num > 0 } 
# => [[1, 2], [1, 4]] 
_.map { |pair| pair[1] } 
# => [2, 4] 
+3

'.map(&:last)'将会替代'.map {| pair |对[1]}'如果你想减少一点噪音。 –

7

我会做

[0, 0, 1, 0, 1].map.with_index{|x, i| i if x > 0}.compact 

如果你想,作为一个单一的方法,Ruby没有内置在一个,但你可以这样做:

class Array 
    def select_indice &p; map.with_index{|x, i| i if p.call(x)}.compact end 
end 

并将其用作:

[0, 0, 1, 0, 1].select_indice{|x| x > 0} 
相关问题