Local variables & blocks

  def weird
    x = nil
    [proc {x}, proc {|x|}]
  end

What does it do?

It returns an array of two procs: one which gives you the current value of
x, and one which sets it to its argument. An attribute reader and an
attribute writer. It's that hidden state I was talking about.

Can you do this in other languages like Scheme, or is it an aberration of
Ruby? That's one thing I'm trying to get a handle on.

Regards,

Brian.

def weird
x = nil
[proc {x}, proc {|x|}]
end

What does it do?

It returns an array of two procs: one which gives you the current value of
x, and one which sets it to its argument. An attribute reader and an
attribute writer. It’s that hidden state I was talking about.

Yes.

Can you do this in other languages like Scheme, or is it an aberration of
Ruby? That’s one thing I’m trying to get a handle on.

Its an important part of being a closure that free variables within the
closure are bound in the scope where the closure is created.

If I recall correctly, Common Lisp (ie. CLOS) takes advantage of this
hidden state feature of closures to create objects. The hidden state
becomes the instance variables of an object (or something like that).

···

On Tue, 2003-02-04 at 04:33, Brian Candler wrote:


– Jim Weirich jweirich@one.net http://w3.one.net/~jweirich

“Beware of bugs in the above code; I have only proved it correct,
not tried it.” – Donald Knuth (in a memo to Peter van Emde Boas)