块中的变量范围 [英] Variable Scope in Blocks

查看:40
本文介绍了块中的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

def block_local_parameterx = 100[1,2,3].each 做 |x|puts "参数 x 是 #{x}"x += 10将重新分配给 x 块;现在是 #{x}"结尾puts "外部 x 的值现在是 #{x}"结尾block_local_parameter

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

<块引用>

参数 x 为 1在块中重新分配给 x;现在是 11参数 x 为 2在块中重新分配给 x;现在是 12参数 x 为 3在块中重新分配给 x;现在是 13外部 x 仍然是 100

我的输出(Ruby 1.8.7):

<块引用>

参数 x 为 1在块中重新分配给 x;现在是 11参数 x 为 2在块中重新分配给 x;现在是 12参数 x 为 3在块中重新分配给 x;现在是 13外部 x 仍然是 13

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

解决方案

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

David A Black (The Well Grounded Rubyist, Chapter 6) presents the following code:

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

Expected output as per the book (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

My output (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

Is the book wrong? Or, am I missing something?

解决方案

What you're seeing is the behavior for Ruby 1.8.x. Variable scope for blocks was introduced in 1.9, switch to 1.9.x and you will get the same results as in the book.

这篇关于块中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆