范围和块 [英] Scopes and blocks

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

问题描述

在 ruby​​ 中,moduleclassdef 关键字定义了一个新的作用域.我很困惑为什么块中定义的局部变量不存在于块之外.块参数是另一个作用域门吗?例如:

In ruby, module, class, and def keywords define a new scope. I'm confused as to why local variables defined in a block do not exist outside of the block. Is a block argument another scope gate? For example:

(1..2).each { |n| numer = 'czesc' }
numer # => NameError: undefined local variable or method `czesc' for main:Object

或者更简单:

def kon; end
kon { kot = 3 }
kot # => NameError: undefined local variable or method `kot' for main:Object

我想,也许它没有被持久化,因为它是在方法的参数中定义的,但以下适用于普通参数:

I thought, maybe it's not persisted because it's defined in the method's arguments, but the following works for the normal arguments:

def pokaz(cos)
  p cos
end
pokaz(co = "to")
co # => "to"

推荐答案

在 ruby​​ 中,moduleclassdef 关键字定义了一个新的作用域.

In ruby, module, class, and def keywords define a new scope.

Ruby 中有六个作用域结构:模块体、类体、方法体和脚本体创建新的作用域,块体和stabby lambda"文字体创建新的嵌套作用域.

There are six scope constructs in Ruby: module bodies, class bodies, method bodies and script bodies create new scopes, block bodies and "stabby lambda" literal bodies create new nested scopes.

我很困惑为什么块中定义的局部变量不存在于块之外.

I'm confused as to why local variables defined in a block do not exist outside of the block.

因为块体有自己的词法作用域.作用域是嵌套的,这意味着它可以从外部作用域访问局部变量,但来自内部作用域的变量永远不会泄漏到外部作用域.

Because a block body has its own lexical scope. The scope is nested, which means that it has access to local variables from the outer scope, but variables from an inner scope never leak into the outer scope.

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

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