gpt4 book ai didi

Ruby 将对象插入现有的已排序对象数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:10:38 26 4
gpt4 key购买 nike

我有以下现有的 Dog 对象数组,它们按 age 属性排序:

class Dog
attr_accessor :age

def initialize(age)
@age = age
end
end

dogs = [Dog.new(1), Dog.new(4), Dog.new(10)]

我现在想插入 一条新的狗记录,并将它放在数组中的正确位置。

假设我想插入这个对象:

another_dog = Dog.new(8)

我想把它插入到数组中,让它成为数组中的第三项。

这是一个人为的示例,旨在演示我特别想如何将一个项目插入到现有的有序数组中。我意识到我可以创建一个全新的数组并重新对所有对象进行排序,但这不是我的目标。

谢谢!

最佳答案

在 Ruby 2.3+ 中,有一个 Array#bsearch_index您可以使用它来确定您需要传递给 Array#insert 的索引:

dogs = [Dog.new(1), Dog.new(4), Dog.new(10)]

another_dog = Dog.new(8)
insert_at = dogs.bsearch_index { |dog| dog.age >= another_dog.age }
dogs.insert(insert_at, another_dog)
puts dogs.inspect
# => [Dog.new(1), Dog.new(4), Dog.new(8), Dog.new(10)]

这仅在数组已经排序时有效(标准,当对任何内容使用二进制搜索时),但听起来确实如此。

如果您使用的是 Ruby < 2.3,您没有 bsearch_index,但是 insert 仍然可用,您可以快速搜索索引您自己的,然后使用 insert

关于Ruby 将对象插入现有的已排序对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46125658/

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