1

我遇到了这个问题,想知道是否有更好的方法来做到这一点。

给定数组:

options = [
  SelectItem.new(-1, "String 1"),
  SelectItem.new(0, "String 2"),
  SelectItem.new(7, "String 3"),
  SelectItem.new(14, "String 4")
]

获取与特定条件匹配的第一个元素的索引的最佳方法是什么?

我的解决方案是:

my_index = 0
options.each_with_index do |o, index|
  if o.value == some_value
    my_index = index
    break
  end
end

还有另一种方法可以做到这一点吗? Enumerable#find返回满足条件的第一个对象,但我想要返回满足条件的第一个对象的索引。

4

2 回答 2

5
a=[100,200,300]
a.index{ |x| x%3==0 }   # returns 2

对于您的情况:

options.index{ |o| o.value == some_value }
于 2013-01-25T23:09:00.990 回答
1

采用Array#index

> a = ['asdf', 'qwer', '1234']
> a.index { |e| e =~ /\d/ }
=> 2
于 2013-01-25T23:13:21.670 回答