I have an object Results that contains an array of result objects along with some cached statistics about the objects in the array. I’d like the Results object to be able to behave like an array. My first cut at this was to add methods like this
def <<(val)
@result_array << val
end
This feels very c-like and I know Ruby has better way.
I’d also like to be able to do this
Results.each do |result|
result.do_stuff
end
but am not sure what the each method is really doing under the hood.
Currently I simply return the underlying array via a method and call each on it which doesn’t seem like the most-elegant solution.
Any help would be appreciated.
For the general case of implementing array-like methods, yes, you have to implement them yourself. Vava’s answer shows one example of this. In the case you gave, though, what you really want to do is delegate the task of handling
each(and maybe some other methods) to the contained array, and that can be automated.This class will get all of Array’s Enumerable behavior as well as the Array
<<operator and it will all go through the inner array.Note, that when you switch your code from Array inheritance to this trick, your
<<methods would start to return not the object intself, like real Array’s<<did — this can cost you declaring another variable everytime you use<<.