Ruby访问嵌套函数中的外部变量 [英] Ruby accessing outer variables in nested function

查看:69
本文介绍了Ruby访问嵌套函数中的外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定对此有一个简单的答案;我只是似乎找不到它.我在Ruby中创建了一个嵌套函数,但在从内部函数内部的外部函数访问变量时遇到了麻烦:

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)

我得到:main:Object` NameError: undefined local variable or method x'

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

类似的Python代码可以正常工作:

The analogous Python code works:

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

foo(5)

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

So how do I do the same thing in Ruby?

推荐答案

据我所知,在函数中定义命名函数并不能访问任何局部变量.

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

您可以改用Proc:

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

foo(5)

这篇关于Ruby访问嵌套函数中的外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆