块中的可变范围

David A Black( The Well Grounded Rubyist ,第6章)提供了以下代码:

def block_local_parameter x = 100 [1,2,3].each do |x| puts "Parameter x is #{x}" x += 10 puts "Reassigned to x in block; it is now #{x}" end puts "The value of outer x is now #{x}" end block_local_parameter 

按照本书的预期输出(Ruby 1.9.1):

 Parameter x is 1 Reassigned to x in block; it's now 11 Parameter x is 2 Reassigned to x in block; it's now 12 Parameter x is 3 Reassigned to x in block; it's now 13 Outer x is still 100 

我的输出(Ruby 1.8.7):

 Parameter x is 1 Reassigned to x in block; it's now 11 Parameter x is 2 Reassigned to x in block; it's now 12 Parameter x is 3 Reassigned to x in block; it's now 13 Outer x is still 13 

这本书错了吗? 或者,我错过了什么?

您所看到的是Ruby 1.8.x的行为。 块的可变范围在1.9中引入,切换到1.9.x,您将获得与书中相同的结果。