gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:02 25 4
gpt4 key购买 nike

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

给定数组:

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 返回满足条件的第一个对象,但我想要返回第一个对象的索引的东西满足条件。

最佳答案

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

针对您的情况:

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

关于Ruby 抓取符合条件的数组第一个元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14531731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com