lambda block doesn't work with upto iterator

E

Ed Loyot

[Note: parts of this message were removed to make it a legal post.]

Hi Folks,

I'm new to Ruby and I'm trying to get a complete understanding of blocks. I
captured some code in a block using lambda and was able to execute the code
with the .time Integer iterator, but I get an exception trying to get it to
work with the .upto iterator. The code is below. Can anyone explain why the
upto call fails but the .times call succeeds.

Excerpt:

proc1 = lambda do |p1|
puts "#{p1}"
end

# This works.
5.times &proc1

# Why does this fail?
0.upto(4) &proc2


Thanks,

Ed

Full Code:

#
# Experiment with blocks!
#
# Tried with ruby verion: ruby 1.8.6 (2007-09-24 patchlevel 111)
[i386-mswin32]
#
# Ed Loyot
#

proc1 = lambda do |p1|
puts "#{p1}"
end

proc2 = Proc.new do |p1|
puts "#{p1}"
end

# Make sure the proc works.
puts "Call proc1!"
proc1.call "112"

puts "Call proc2!"
proc2.call "212"

# Try it with an iterator.
puts "Call proc1 with times iterator!"
5.times &proc1

puts "Call proc2 with times iterator!"
5.times &proc2

# Why does this fail?
begin
puts "Call proc1 with upto iterator!"
0.upto(4) &proc1
rescue StandardError => error
puts "Caught error: " + error
end

# Why does this fail?
begin
puts "Call proc2 with upto iterator!"
0.upto(4) &proc2
rescue StandardError => error
puts "Caught error: " + error
end
 
S

Sebastian Hungerecker

Ed said:
# Why does this fail?
0.upto(4) &proc2

It has to be 0.upto(4,&proc2) or 0.upto 4, &proc2
In other words: syntax-wise a &-proc is treated like just another argument
(although it has to come last in the argument list), not like a block.

HTH,
Sebastian
 
R

Rados³aw Bu³at

PiA1LnRpbWVzICZwcm9jMgppcyB0aGUgc2FtZSBhcwo+IDUudGltZXMoJnByb2MyKQoKPiAwLnVw
dG8oNCkgJnByb2MxCmNoYW5nZSB0bwo+IDAudXB0byg0LCAmcHJvYzEpCgpJdCBzaG91bGQgd29y
a3MuCkkgZ3Vlc3MgdGhhdCAiMC51cHRvKDQpICZwcm9jMSIgaXMgcGFyc2VkIGJ5IFJ1YnkgbGlr
ZSBiaXR3aXNlIGFuZAp3aXRoIGxlZnQgb3BlcmFuZCAiMC51cHRvKDQpIiBhbmQgcmlnaHQgb3Bl
cmFuZCAicHJvYzEiLgoKLS0gClJhZG9zs2F3IEJ1s2F0CgpodHRwOi8vcmFkYXJlay5qb2dnZXIu
cGwgLSBt82ogYmxvZwo=
 

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

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top