【问题标题】:Variable Scope in Blocks块中的变量范围
【发布时间】:2011-06-06 15:23:29
【问题描述】:

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】:

您看到的是 Ruby 1.8.x 的行为。块的可变作用域是在 1.9 中引入的,切换到 1.9.x,你会得到与书中相同的结果。

【讨论】:

  • 哦...顺便说一句,在 Ruby 1.8.x 中有一种方法可以在块中声明一个变量(x),这样我就不会最终更改另一个 x 变量?跨度>
  • @Prakhar:没有。该功能是在 1.9 中添加的。
猜你喜欢
  • 1970-01-01
  • 2019-09-10
  • 2013-05-10
  • 1970-01-01
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
相关资源
最近更新 更多