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

前端 未结 7 1632
抹茶落季
抹茶落季 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:41

    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.

    require 'forwardable'
    
    class Results
      include Enumerable
      extend Forwardable
      def_delegators :@result_array, :each, :<<
    end
    

    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 <<.

提交回复
热议问题