How do I add 'each' method to Ruby object (or should I extend Array)?

前端 未结 7 1496
抹茶落季
抹茶落季 2021-01-30 04:00

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

7条回答
  •  面向向阳花
    2021-01-30 04:42

    This feels very c-like and I know Ruby has better way.

    If you want an object to 'feel' like an array, than overriding << is a good idea and very 'Ruby'-ish.

    but am not sure what the each method is really doing under the hood.

    The each method for Array just loops through all the elements (using a for loop, I think). If you want to add your own each method (which is also very 'Ruby'-ish), you could do something like this:

    def each
      0.upto(@result_array.length - 1) do |x|
        yield @result_array[x]
      end
    end
    

提交回复
热议问题