Ruby块示例不能正常工作

age*_*eto 3 ruby scope

我刚开始学习不同资源的红宝石阅读.其中一个是rubylearning.com,我只是阅读块部分并进行练习.出于某种原因,这个示例的范围在我的情况下有不同的工作方式:

x = 10  
5.times do |x|  
  puts "x inside the block: #{x}"  
end  

puts "x outside the block: #{x}"  
Run Code Online (Sandbox Code Playgroud)

输出应该是(根据网站):

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  
Run Code Online (Sandbox Code Playgroud)

但我的输出是:

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
Run Code Online (Sandbox Code Playgroud)

知道为什么吗?本节应该是关于红宝石块的范围,但我现在完全糊涂了......

编辑:

好吧我刚才意识到:我正在从textmate执行我的代码.如果我从命令行运行它,我得到预期的结果,加上1.9.2 RUBY_VERSION.但我从Textmate运行1.8.7.有textmate自己安装的ruby版本还是什么? - 0al0 0秒前编辑

JCo*_*era 5

您的示例适用于ruby 1.9.1,因为文章解释说:

在Ruby 1.9.1中,块仅为块参数引入了自己的范围.

所以你正在使用另一个ruby版本,试试这个:

ruby -v
Run Code Online (Sandbox Code Playgroud)

我建议安装rvm来管理不同的ruby版本.