简体   繁体   English

符合条件的数组的第一个元素的Ruby抓取索引

[英]Ruby grab index of first element of an array that matches criteria

I ran across this issue and am wondering if there is a better way to do it. 我遇到了这个问题,想知道是否有更好的方法可以做到这一点。

Given the array: 给定数组:

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

What is the best way to grab the index of the first element that matches a certain criteria? 获取与特定条件匹配的第一个元素的索引的最佳方法是什么?

My solution was: 我的解决方案是:

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

Is there another way to do this? 还有另一种方法吗? Enumerable#find returns the first object that satisfies the condition, but I want something that returns the index of the first object that satisfies the condition. Enumerable#find返回满足条件的第一个对象,但是我想要一些返回满足条件的第一个对象的索引的对象。

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

for your case: 对于您的情况:

options.index{ |o| o.value == some_value }

Use Array#index 使用Array#index

> a = ['asdf', 'qwer', '1234']
> a.index { |e| e =~ /\d/ }
=> 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM