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

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

    If you really do want to make your own #each method, and assuming you don't want to forward, you should return an Enumerator if no block is given

    class MyArrayLikeClass
      include Enumerable
    
      def each(&block)
        return enum_for(__method__) if block.nil?
        @arr.each do |ob|
          block.call(ob)
        end
      end
    end
    

    This will return an Enumerable object if no block is given, allowing Enumerable method chaining

提交回复
热议问题