0

I thought when you called a proc within a method the return value of the proc would trigger a return from the out block context that called the proc. When I call test(a_block) I feel like the puts "after the block" should not be executed as there was a return value from the proc. Further... test(a_block) and test(b_block) behave exactly the same. I thought there was supposed to be a difference here?

a_block = Proc.new do
  puts "in the Proc"
  55
end

b_block = lambda do 
  puts "in the lambda"
  66
end

def test(block)

  puts "in test"
  puts block.call
  puts "after the block"
  99 
end

puts test(a_block)
puts test(b_block)
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
slindsey3000
  • 4,053
  • 5
  • 36
  • 56
  • Put 'return' in every block and you'll see the difference. – megas Dec 04 '11 at 17:54
  • 1
    possible duplicate of [What's the difference between a proc and a lambda in Ruby?](http://stackoverflow.com/questions/1740046/whats-the-difference-between-a-proc-and-a-lambda-in-ruby) – Andrew Grimm Dec 04 '11 at 21:50

2 Answers2

1

the return value

in your first sentence should read as

the return statement

Use return 66 and return 55 and you will see the light!

A great investigation on Ruby closures can be found here: http://innig.net/software/ruby/closures-in-ruby.rb

Oleg Mikheev
  • 17,186
  • 14
  • 73
  • 95
0

According to this question, they should behave entirely the same in your example. The only notable difference is that lambda checks the number of arguments when called, whereas Proc.new spits out an undefined method error.

Note that I'm not an expert Ruby-ist. I read your question, and then clicked on the first "related" link in the sidebar that looked helpful. Please search more carefully in the future.

Community
  • 1
  • 1
semisight
  • 914
  • 1
  • 8
  • 15