我的理解是,ruby块具有块范围,并且块内创建的所有变量将仅在块内生效.
示例:
food = ['toast','cheese','wine'] food.each { |food| puts food.capitalize} puts food
输出:
"Toast" "Cheese" "Wine" "Wine"
如果你把块里的食物变量(每个块),我的理解是它有阻止的范围.它只在封闭范围内,对外在的可变食物没有任何影响.
但是行为是不同的,在这种情况下修改了名为food的外部变量.这个理解是否正确,在红宝石中我们有阻挡范围吗?
解决方法
这是ruby 1.8的预期行为.
It was fixed
in 1.9.以下的代码片段以红宝石1.9.3运行
food = ['toast','wine'] food.each { |food| puts food.capitalize.inspect} # !> shadowing outer local variable - food puts food.inspect # >> "Toast" # >> "Cheese" # >> "Wine" # >> ["toast","cheese","wine"]
你是正确的,从块的食物被限定到该块,并用这个名字影响其他变量.但是如果你做了一些破坏性的东西,它将被反映在原始的数组中,因为它是引用数组元素而不是它的副本.注意:
food = ['toast','wine'] food.each { |f| f.capitalize} # transform and discard food # => ["toast","wine"] food.each { |f| f.capitalize! } # transform destructively (bang-version) food # => ["Toast","Cheese","Wine"]