I am studying Ruby, and typed a piece of code to experiment with block-scoped variables:
x = 10
3.times do |i; x|
x = x + 1
puts("inside block is #{x}")
end
puts("outside block is #{x}")
I would expect the x block variable to automatically capture the value of the x global variable, and then x inside the block to be 11 every time, and x outside the block to be protected, and stay at 10. This "shielding" action is what is described in many Ruby tutorials found throughout the web.
But instead, the script fails, telling me that x is nil and that it doesn't have a + function. In other words, the x block variable hasn't been initialized with a value.
The exact code above is in a file called delete_me.rb, and ran with:
ruby delete_me.rb
When I run the script, I get the following error:
delete_me.rb:3:in `block in <main>': undefined method `+' for nil:NilClass (NoMethodError)
from delete_me.rb:2:in `times'
from delete_me.rb:2:in `<main>'
How do I initialize the value of a block variable in Ruby?