46

I'm sure there's a simple answer for this; I just can't seem to find it. I made a nested function in Ruby, and I was having trouble accessing variables from the outer function inside the inner function:

def foo(x)
  def bar
    puts x
  end
  bar
  42
end

foo(5)

I get: NameError: undefined local variable or methodx' for main:Object`

The analogous Python code works:

def foo(x):
  def bar():
    print x
  bar()
  return 42

foo(5)

So how do I do the same thing in Ruby?

user102008
  • 30,736
  • 10
  • 83
  • 104
  • 10
    An important (but subtle) distinction here is that def...end defines a method, not a function. use lambda/proc to define functions and capture local variables in a closure, as tadman shows. – rampion Jun 19 '09 at 05:30

1 Answers1

55

As far as I know, defining a named function within a function does not give you access to any local variables.

What you can do instead is use a Proc:

def foo(x)
  bar = lambda do
    puts x
  end
  bar.call
  42
end

foo(5)
tadman
  • 208,517
  • 23
  • 234
  • 262