sil*_*son 1 ruby arrays indexing
我遇到了这个问题,我想知道是否有更好的方法来做到这一点.
鉴于阵列:
options = [
SelectItem.new(-1, "String 1"),
SelectItem.new(0, "String 2"),
SelectItem.new(7, "String 3"),
SelectItem.new(14, "String 4")
]
Run Code Online (Sandbox Code Playgroud)
获取匹配特定条件的第一个元素的索引的最佳方法是什么?
我的解决方案是:
my_index = 0
options.each_with_index do |o, index|
if o.value == some_value
my_index = index
break
end
end
Run Code Online (Sandbox Code Playgroud)
还有另一种方法吗? Enumerable#find返回满足条件的第一个对象,但我想要一些返回满足条件的第一个对象的索引.
a=[100,200,300]
a.index{ |x| x%3==0 } # returns 2
Run Code Online (Sandbox Code Playgroud)
对于你的情况:
options.index{ |o| o.value == some_value }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2745 次 |
| 最近记录: |