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]}'如果你想减少一点噪音。 –