2011-06-28 70 views
3

我刚刚开始学习从不同资源读取ruby。其中之一是rubylearning.com,我刚刚阅读blocks section并进行练习。出于某种原因,这个例子的范围在我的案子是不同的:Ruby块不能正常工作

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

puts "x outside the block: #{x}" 

输出应(根据现场):

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 

但我的输出是:

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 

任何想法为什么?这部分应该是关于红宝石块的范围,但我完全糊涂了,现在......

编辑:

好,我才意识到事情:我是从TextMate的执行我的代码。如果我从命令行运行它,我会得到预期的结果,再加上1.9.2 RUBY_VERSION。但我从Textmate得到1.8.7。有textmate自己的版本的红宝石安装或什么的? - 0al0 0秒前编辑

+0

您使用的是哪个版本的Ruby? – Dogbert

+0

红宝石1.9.2,根据ruby -v –

+0

你肯定*关于这个?在Ruby 1.9.2中,你应该得到第一个(预期的)结果。 (Ruby 1.8.x会输出第二个版本) – levinalex

回答

5

你的榜样,因为工作1.9.1如文章解释:

在Ruby 1.9.1,块介绍自己 自己的范围仅为块参数 。

所以,你与另一个红宝石版工作,试试这个:

ruby -v 

我建议安装rvm管理不同的Ruby版本。

4

您正在使用过时的Ruby版本。块本地变量的范围在Ruby 1.9.0+中已经更改。