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