What am I missing with this closure example?

S

Sam Kong

Hello!

Since my last question about
closure(http://groups.google.com/group/comp...1683e/12e182a6ff493232?hl=en#12e182a6ff493232)
I am testing my understanding making some examples.

Here's some code:

def f name
x = 0

case name
when "one"
lambda {x += 1; puts x}
when "two"
lambda {puts x}
end
end

one = f "one"
two = f "two"

one.call
two.call
one.call
two.call

Result:

1
0
2
0


I expected the following.
1
1
2
2


I thought that x is shared between one and two but they don't seem to.
Or am I missing something?

Thanks.

Sam
 
K

konsu

hello,

f("two") creates a lambda that sees 'x' as it was at the time of its
creation. zero that is.

the 'x' that f("one") uses is in a different closure.

konstantin
 
H

hitesh.jasani

Like konsu states, you have two different closures. Here's a little
rewrite of your code that works with one closure.

def f
x = 0
one = lambda {x += 1; puts x}
two = lambda {puts x}
[one, two]
end

one, two = f

one.call
two.call
one.call
two.call


=> with results of
1
1
2
2


- Hitesh
http://www.jasani.org/
 
M

Mike Stok

Hello!

Since my last question about
closure(http://groups.google.com/group/comp.lang.ruby/browse_frm/
thread/0d7e258107e1683e/12e182a6ff493232?hl=en#12e182a6ff493232)
I am testing my understanding making some examples.

Here's some code:

def f name
x = 0

case name
when "one"
lambda {x += 1; puts x}
when "two"
lambda {puts x}
end
end

one = f "one"
two = f "two"

one.call
two.call
one.call
two.call

Result:

1
0
2
0


I expected the following.
1
1
2
2


I thought that x is shared between one and two but they don't seem to.
Or am I missing something?

Each time you call f you get a different x, so the lambda's x are
bound to different variables. Does this do what you expect:

def f
x = 0

[lambda {x += 1; puts x}, lambda {puts x}]
end

one, two = f

one.call
two.call
one.call
two.call


Mike

--

Mike Stok <[email protected]>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.
 
S

Sam Kong

Like konsu states, you have two different closures. Here's a little
rewrite of your code that works with one closure.

def f
x = 0
one = lambda {x += 1; puts x}
two = lambda {puts x}
[one, two]
end

one, two = f

one.call
two.call
one.call
two.call


=> with results of
1
1
2
2

Aha~
Now I see the difference.
Thanks everyone.

Sam
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top