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

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

    each just goes through array and call given block with each element, that is simple. Since inside the class you are using array as well, you can just redirect your each method to one from array, that is fast and easy to read/maintain.

    class Result
        include Enumerable
    
        def initialize
            @results_array = []
        end
    
        def <<(val)
            @results_array << val
        end
    
        def each(&block)
            @results_array.each(&block)
        end
    end
    
    r = Result.new
    
    r << 1
    r << 2
    
    r.each { |v|
       p v
    }
    
    #print:
    # 1
    # 2
    

    Note that I have mixed in Enumerable. That will give you a bunch of array methods like all?, map, etc. for free.

    BTW with Ruby you can forget about inheritance. You don't need interface inheritance because duck-typing doesn't really care about actual type, and you don't need code inheritance because mixins are just better for that sort of things.

提交回复
热议问题