Lambda block doesn't work with upto iterator

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

Ed Loyot wrote:

# 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

···

--
Jabber: sepp2k@jabber.org
ICQ: 205544826

0.upto(4,&proc2)

Farrel

···

On 17/01/2008, Ed Loyot <eloyot@gmail.com> wrote:

# This works.
5.times &proc1

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

5.times &proc2

is the same as

5.times(&proc2)

0.upto(4) &proc1

change to

0.upto(4, &proc1)

It should works.
I guess that "0.upto(4) &proc1" is parsed by Ruby like bitwise and
with left operand "0.upto(4)" and right operand "proc1".

···

--
Radosław Bułat

http://radarek.jogger.pl - mój blog