jaz*_*esh 7 ruby python closures python-nonlocal
我试图在Ruby中编写一个闭包.这是用Python编写的代码:
def counter():
x = 0
def increment(y):
nonlocal x
x += y
print(x)
return increment
Run Code Online (Sandbox Code Playgroud)
在Ruby中是否存在"非本地"等价物,因此我可以从内部增量访问变量x并对其进行更改?
关键字nonlocal告诉 Python 要捕获哪些变量。在 Ruby 中,您不需要这样的关键字:除非另有明确提及,否则所有变量都会被捕获。
因此,与 Python 代码等效的 Ruby 几乎可以直接翻译:
counter = -> {
x = 0
->y {
x += y
puts x
}
}
i = counter.()
i.(2)
# 2
i.(3)
# 5
Run Code Online (Sandbox Code Playgroud)
不过,使用 for 的方法可能会更惯用counter:
def counter
x = 0
->y {
x += y
puts x
}
end
i = counter
i.(2)
# 2
i.(3)
# 5
Run Code Online (Sandbox Code Playgroud)