I am trying to write a closure in Ruby. This is the code written in Python:
def counter():
x = 0
def increment(y):
nonlocal x
x += y
print(x)
return increment
Is there a “nonlocal” equivalent in Ruby so I can access and make changes to the variable x from inside increment?
The
nonlocalkeyword tells Python which variables to capture. In Ruby, you don’t need such a keyword: all variables are captured unless explicitly mentioned otherwise.So, the Ruby equivalent to your Python code translates almost directly:
It would probably be more idiomatic to use a method for
counter, though: