0

Possible Duplicate:
Using 'return' in a Ruby block

I'm new to Ruby, and was surprised that this snippet raise a LocalJumpError when the block return:

$bail_if = proc { |condition|
  if condition
    puts 'the condition is true'
    return
  else
    puts 'the condition is false'
  end
}

def method some_condition
  $bail_if[some_condition]
end

method true

If I defined bail_if as a local variable in def method, then there is no problem. Why is this?

Community
  • 1
  • 1
sivabudh
  • 31,807
  • 63
  • 162
  • 228
  • 1
    Works for me on ruby 1.8.7. Are you running ruby 1.9? – Alex Wayne Dec 01 '11 at 20:53
  • Woops, forgot to mention that I'm using 1.9.2p290. Thanks! – sivabudh Dec 01 '11 at 20:55
  • 1
    Are you asking this because you want `method` to return if `some_condition` is true, but to continue running the rest of the `method` method otherwise? By the way, `method` isn't an ideal name, because there's already [a method called method](http://www.ruby-doc.org/core-1.9.3/Object.html#method-i-method) – Andrew Grimm Dec 01 '11 at 22:20
  • 1
    @Squeegy: That's because `proc` behaves differently in 1.8 and 1.9 - in 1.8 it returns a lambda, and in 1.9 it returns a proc. See bullet point 2 [here](http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/) – Andrew Grimm Dec 02 '11 at 01:32
  • @AndrewGrimm, yes I'm asking this because I want `method` to return if `some_condition` is true, but to continue running the rest of the `method` otherwise. – sivabudh Dec 02 '11 at 15:37

2 Answers2

2

Change your proc { |condition| to lambda { |condition|. proc-object has a block semantic, whereas lambda object has method semantic. Because the proc object is like a block, when you call a proc that executes a return statement, it attempts to return from the method that encloses the block that was converted to the proc. You don't have such method in your first case and as consequence you get LocalJumpError. When you define your proc as a local variable in your method, all is working fine.

WarHog
  • 8,622
  • 2
  • 29
  • 23
2

You don't return from a proc (aka block) in ruby 1.9. Getting rid of that explicit return seems to fix it. But that return is totally useless here anyway.

Or if you do need an explicit return, use a lambda instead like @WarHog suggests.

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337