Ruby访问嵌套函数中的外部变量

时间:2022-04-17 15:55:53

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:

我相信有一个简单的答案;我就是找不到。我用Ruby做了一个嵌套函数,在内部函数的外部函数访问变量时遇到了麻烦:

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

foo(5)

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

我得到:NameError: undefined local变量或methodx' for main:Object '

The analogous Python code works:

类似的Python代码可以工作:

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

foo(5)

So how do I do the same thing in Ruby?

那么我如何在Ruby中做同样的事情呢?

1 个解决方案

#1


45  

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:

相反,你能做的是使用Proc:

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

foo(5)

#1


45  

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:

相反,你能做的是使用Proc:

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

foo(5)