当块已经有自己的作用域时,设置 Ruby 块局部变量的目的是什么?

2023-12-29

Learning about Ruby blocks here http://rubylearning.com/satishtalim/ruby_blocks.html. What is the point of having block local variable in this example: enter image description here

When you can just do the below instead? The x in the block is already going to have its own scope, which is different than the x that is outside the block. enter image description here


块作用域nest在它们的词法封闭范围内:

foo = :outerfoo
bar = :outerbar

1.times do |;bar|
  foo = :innerfoo
  bar = :innerbar
  baz = :innerbaz
end

foo #=> :innerfoo
bar #=> :outerbar
baz # NameError

您需要一种方法来告诉 Ruby:“我不需要外部作用域中的这个变量,我想要一个新的变量。”这就是块局部变量的作用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当块已经有自己的作用域时,设置 Ruby 块局部变量的目的是什么? 的相关文章

随机推荐