A. S. Bradbury
8/1/2006 4:06:00 PM
On Tuesday 01 August 2006 16:43, Michael Saltzman wrote:
> Am new to Ruby and have the folloiwng Question.
>
> I have a class, say Collect, and I want to mixin Enumerable. How do I
> write the each method in Collect?
>
> class Collect
> include Enumerable
> def initialize()
> @array = Array.new(0)
> @ct = 0
> end
> def add(item)
> @array.push(item)
> @ct += 1
> end
> def howmany
> @ct
> end
> def each
> #
> # Not sure how to do this????
> #
> end
> end
It depends what you want each to do? Just to wrap @array.each? In that case,
this would work:
def each
@array.each {|item| yield item}
end
Of course you can do whatever you want to the array item in the block before
you yield it again.
An alternative technique is as follows:
def each(&block)
@array.each(&block)
end
I'm sure someone will correct me if I describe this slightly wonky, but the
basic idea is that the interpreter converts the block argument to a proc with
a name (I think I read an article that claimed a block is always converted to
a proc, but when no &arg is given, it is simply a proc with no name,
accessible of course via yield). This is then passed on to @array.each as a
block argument.
I don't know whether there are any real advantages or disadvantages to either
method. Hope this helps
Alex