3
給定一個數組[0, 0, 1, 0, 1]
,是否有一個內置的方法來獲取大於0的所有索引值?所以,該方法應返回[2, 4]
。如何爲一個Ruby數組中的多個值做find_index?
find_index
只返回第一個匹配。
使用Ruby 1.9.2。
給定一個數組[0, 0, 1, 0, 1]
,是否有一個內置的方法來獲取大於0的所有索引值?所以,該方法應返回[2, 4]
。如何爲一個Ruby數組中的多個值做find_index?
find_index
只返回第一個匹配。
使用Ruby 1.9.2。
在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]
我會做
[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}
'.map(&:last)'將會替代'.map {| pair |對[1]}'如果你想減少一點噪音。 –