2011-06-28 67 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+中已經更改。