develooper Front page | perl.perl6.internals | Postings from July 2002

Ruby iterators and blocks (was: Perl 6 Summary)

Thread Previous | Thread Next
From:
Andy Wardley
Date:
July 4, 2002 02:20
Subject:
Ruby iterators and blocks (was: Perl 6 Summary)
Message ID:
20020704101918.G4488@dog.ourshack.com
On Tue, Jul 02, 2002 at 03:20:35PM -0500, Dan Sugalski wrote:
> I'm pretty sure the iterators they build are just closures with named 
> arguments, and behave as any other closure would behave. 

Not quite.  Ruby iterators expect a block.  This is very much like a closure
except that block parameters are local to the scope in which the block is 
defined, not lexically scoped within the block.

Or in other words, any existing variable of the same name as a block parameter
will be updated when the block is called.

An example:

  n = 10

  def twice
    yield 1
    yield 2
  end

  twice { |n| puts "Hello World #{n}" }

  puts "n is now #{n}"

The result of this is:

  Hello World 1
  Hello World 2
  n is now 2

I personally believe this approach is flawed, especially considering the fact 
that there is no way (that I know of) to force block parameters to be truly
lexically scoped or temporary (i.e. 'my' or 'local' in Perlspeak).  Much too 
easy to mangle existing variables like this.

A


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About