目标:定义一个方法
next_objects(object, object_index, objects)
objects
的一部分,并且在集合中具有其索引值,并从集合中查找接下来的 N 个值。neighbours
,它将确定要查找的索引范围next_indicies = 1..object.neighbours
quantity
聚合在一个数组中。
这怎么能投?
我认为,多思考一下是否有更好的方法来模拟您想要的行为,您可能会受益。
根据我从您的请求中收集到的信息,以下代码应该可以满足您的要求。这不是特别惯用的 Ruby。
class Foo
attr_reader :quantity, :neighbours
def initialize(quantity: 0, neighbours: 0)
@quantity = quantity
@neighbours = neighbours
end
end
def next_objects(object, object_index, objects)
objects.slice(object_index + 1, object.neighbours).map(&:quantity)
end
objects = [
foo1 = Foo.new(quantity: 5, neighbours: 4),
foo2 = Foo.new(quantity: 10, neighbours: 2),
foo3 = Foo.new(quantity: 15, neighbours: 2),
foo4 = Foo.new(quantity: 20, neighbours: 1),
foo5 = Foo.new(quantity: 25, neighbours: 0),
]
next_objects(foo2, 1, objects)
#=> [15, 20]