如何在 Ruby 数组中查找多个值的索引?

3
给定一个数组[0, 0, 1, 0, 1],是否有内置方法可以获取所有大于0的值的索引?因此,该方法应返回[2, 4]find_index只返回第一个匹配项。
在Ruby 1.9.2中工作。
2个回答

13

在 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| pair[1] } 的好选择。 - mu is too short

7

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}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接