如何在Ruby数组中为多个值执行find_index?

B S*_*ven 3 ruby arrays ruby-on-rails find

给定一个数组[0, 0, 1, 0, 1],是否有内置方法来获取大于0的所有值的索引?所以,该方法应该返回[2, 4].

find_index 只返回第一场比赛.

在Ruby 1.9.2中工作.

Mic*_*ley 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]
Run Code Online (Sandbox Code Playgroud)

单步执行:

[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]
Run Code Online (Sandbox Code Playgroud)

  • `.map(&:last)`将是`.map {| pair |的替代品 对[1]}`如果你想减少一点噪音. (3认同)

saw*_*awa 7

我会做

[0, 0, 1, 0, 1].map.with_index{|x, i| i if x > 0}.compact
Run Code Online (Sandbox Code Playgroud)

如果你想将它作为一个单一的方法,ruby没有内置的方法,但你可以这样做:

class Array
    def select_indice &p; map.with_index{|x, i| i if p.call(x)}.compact end
end
Run Code Online (Sandbox Code Playgroud)

并将其用作:

[0, 0, 1, 0, 1].select_indice{|x| x > 0}
Run Code Online (Sandbox Code Playgroud)