B S*_*ven 3 ruby arrays ruby-on-rails find
给定一个数组[0, 0, 1, 0, 1],是否有内置方法来获取大于0的所有值的索引?所以,该方法应该返回[2, 4].
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]
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)
我会做
[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)
| 归档时间: |
|
| 查看次数: |
4502 次 |
| 最近记录: |