Reputation: 38540
Following code works
def lab
Proc.new { return "foo1" }.call
return "foo2"
end
puts lab #=> foo1
Following does NOT work. Why?. I get LocalJumpError
class Foo
def self.doit(p)
p.call
end
end
p = Proc.new {
return 'from block'
}
a = Foo.doit(p)
puts a #=> LocalJumpError: unexpected return
Upvotes: 2
Views: 177
Reputation: 81651
If you want to get an expression from a proc, as well as doing
p = Proc.new{ "from block" }
like Chubas suggested, you can also use next
, for example
p = Proc.new do
next "lucky" if rand < 0.5 #Useful as a guard condition
"unlucky"
end
Upvotes: 1
Reputation: 18053
It's the difference between procs vs lambdas (Googling that will get you to a plentiful more of resources).
Basically, in the first case, your "return foo1" is returning from lab, and needs to be inside a context where to return.
You can achieve what you're trying to do using a lambda
p = lambda { return "from block" }
Also, note that you usually don't need a return
statements in procs nor lambdas; they will return the last evaluated expression. So, it is equivalent to:
p = Proc.new{ "from block" }
Upvotes: 2
Reputation: 46985
Basically in the second case, you return from the Proc object before you make the call in Foo.doit(p). Since p has already returned p.call has nothing to return to.
Upvotes: 0