tags:

views:

38

answers:

3
+2  Q: 

ruby proc issue

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
A: 

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.

ennuikiller
+2  A: 

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" }
Chubas
+1  A: 

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
Andrew Grimm