块中的可变范围

时间:2011-06-06 15:23:30

标签: ruby

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
这本书错了吗?或者,我错过了什么?

1 个答案:

答案 0 :(得分:8)

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