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
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
Also, note that you usually don’t need a
returnstatements in procs nor lambdas; they will return the last evaluated expression. So, it is equivalent to: