我有一个简单的 ruby 数组,我想选择数组中匹配值正下方的元素。
numbers = [1,2,3,4,5,6,10]
我拥有的匹配值是 10,但我希望能够改为获取 10 之前的值,即 6。
numbers.some_magical_ruby_method {|n| n == 10} # I hope to return 6 since it's the element before 10
我的问题是 Ruby 有什么方法可以让我在匹配值之前选择值。
最佳答案
您可以将 Array#take
与 Array#index
一起使用:
> numbers.take(numbers.index(10).to_i).last
=> 6
如果未找到值,则返回值为 nil
。
关于arrays - 获取数组中恰好低于匹配值的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37213467/