Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby blocks example not working as it is supposed to

Tags:

scope

ruby

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

like image 569
agente_secreto Avatar asked Dec 04 '25 21:12

agente_secreto


1 Answers

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.

like image 175
JCorcuera Avatar answered Dec 06 '25 16:12

JCorcuera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!