2011-12-13 40 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} 
相關問題