给定一个数组
在Ruby 1.9.2中工作。
[0, 0, 1, 0, 1]
,是否有内置方法可以获取所有大于0的值的索引?因此,该方法应返回[2, 4]
。
find_index
只返回第一个匹配项。在Ruby 1.9.2中工作。
[0, 0, 1, 0, 1]
,是否有内置方法可以获取所有大于0的值的索引?因此,该方法应返回[2, 4]
。
find_index
只返回第一个匹配项。在 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]
I would do
[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| pair[1] }
的好选择。 - mu is too short