Hi --

On Wed, 11 Dec 2002, Jake wrote:

> Hi all,
>
> First, here's a piece of working code that prints the values "1 2 3"
> as one would expect:
>
>
> class Array
>   def each2
>     each {|value| puts value}
>   end
> end
> [1, 2, 3].each2
>
>
> **HOW IN THE NAME OF ALAN TURING DOES _each2_ PASS _value_ TO
> _each_***?!?!  I could see how it works if the string ".each2" were
> literally replaced with ".each {|value| puts value}" (ala tcl), but
> everything i think i know about method calls tells me that its
> probably not that simple.

It's actually simpler :-)  Any time you call 'each' on an array, with
a code block, the code blocks gets called once for each element of the
array.  So, all you're doing in each2 is iterating through the array.

It might help to look at it this way:

  class Array
    def each2
      self.each {|value| puts value}    # note the 'self'
    end
  end

(The 'self' is optional here because it's clear that 'each' is being
called on self.)


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav