Reputation: 8079
I have just started learning ruby reading from different resources. One of them is rubylearning.com, and I was just reading the blocks section and doing the exercises. For some reason, this example's scope is working differently in my case:
x = 10
5.times do |x|
puts "x inside the block: #{x}"
end
puts "x outside the block: #{x}"
The output should be ( according to the site):
x inside the block: 0
x inside the block: 1
x inside the block: 2
x inside the block: 3
x inside the block: 4
x outside the block: 10
But my output is:
x inside the block: 0
x inside the block: 1
x inside the block: 2
x inside the block: 3
x inside the block: 4
x outside the block: 4
Any idea why? This section is supposed to be about the scope in ruby blocks, but I am totally confused now...
EDIT:
Ok I just realized something: I was executing my code from textmate. If i run it from the command line i get the expected result, plus 1.9.2 RUBY_VERSION. But I get 1.8.7 running it from Textmate. Has textmate its own version of ruby installed or something? – 0al0 0 secs ago edit
Upvotes: 3
Views: 243
Reputation: 6834
Your example works since ruby 1.9.1 as the article explain:
In Ruby 1.9.1, blocks introduce their own scope for the block parameters only.
So you are working with another ruby version, try this:
ruby -v
I recommend to install rvm to manage different ruby versions.
Upvotes: 5
Reputation: 369458
You are using an outdated version of Ruby. The scope of block local variables has changed in Ruby 1.9.0+.
Upvotes: 4