I’m kind of confused about how scoping works in Ruby. Which Ruby scoping rules prevent the following code from printing out the value of x?
#!/usr/bin/ruby
x = 5
def test
puts "x = #{x}"
end
test # => undefined local variable or method `x' for main:Object
The equivalent Python script does print the value of x:
#!/usr/bin/python
x = 5
def test():
print "x = %s" % x
test() # => x = 5
See “Ruby classes, include, and scope” for more information about Ruby’s scoping and scope gating.
There are a few ways to provide visibility to your test function. One is to make the variable an instance variable:
And another is to use a closure with lambda:
or Proc.new()
For the differences between lambda and Proc.new, see “When to use lambda, when to use Proc.new?“.