ruby

method for finding nearby objects in a collection


Goal: define a method next_objects(object, object_index, objects)
where the object is part of the collection objects and has its index value within the collection, and find the next N values from the collection.
The object has an attribute neighbours which would determine the range of indexes to lookup
next_indicies = 1..object.neighbours
and then aggregate in an array the attribute quantity of the object.

Example data:

id: 338 quantity: 60, neighbours: 3  
id: 339 quantity: 40, neighbours: 2
id: 340 quantity: 29, neighbours: 6
id: 341 quantity: 13, neighbours: 1
id: 342 quantity: 19, neighbours: 4
id: 343 quantity: 18, neighbours: 2
id: 344 quantity: 37, neighbours: 0
id: 345 quantity: 88, neighbours: 1
id: 346 quantity: 42, neighbours: 0

thus object with id 340, would generate an array of [13,19,18,37,88,42]
object id 343, would have array of [37,88]
object id 344, would have []

How could this be cast?


Solution

  • I think you might benefit from thinking a little bit more about whether there's a better way to model the behavior you want.

    From what I could glean from your request, the following code should do what you want. It is not particularly idiomatic 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]