Ruby中的block与变量作用域

按照我们一般的思维模式,特别是在大量使用了Java等高级强静态语言后,可能对变量作用域有很好的理解。

但是在Ruby中,我们会发现一些不同往常经验的例子。

系统环境 写道
ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux]
 

请看这个例子:

#test the block

verb='rescued'
['sedated', 'powdered', 'electrocuted'].
each do |verb|
  puts 'Dr. Cham ' + verb + ' his niece Hannah.'
end
puts 'Yes, Dr. Cham ' + verb + ' his niece Hannah.'
if true then
  verb = 'In the if'
end
puts 'After the if-then-end statement ' + verb

 首先我们不运行,来人为想像一下这个的输出,深深都到Java影响的话可能会得到这样一个结果:

猜想的结果 写道
Dr. Cham sedated his niece Hannah.
Dr. Cham powdered his niece Hannah.
Dr. Cham electrocuted his niece Hannah.
Yes, Dr. Cham rescued his niece Hannah.
After the if-then-end statement In the if

 那么让我们来运行一下看看真实的情况:

真实输出 写道
Dr. Cham sedated his niece Hannah.
Dr. Cham powdered his niece Hannah.
Dr. Cham electrocuted his niece Hannah.
Yes, Dr. Cham electrocuted his niece Hannah.
After the if-then-end statement In the if

 很奇怪吧,从感觉上,虽然我们在各个block中定义了局部变量,但是从表现上来看始终就一个变量在工作。其实也不是,看看这个例子的简单变形(就去掉了第一行的代码):

#test the block

#verb='rescued'
['sedated', 'powdered', 'electrocuted'].
each do |verb|
  puts 'Dr. Cham ' + verb + ' his niece Hannah.'
end
puts 'Yes, Dr. Cham ' + verb + ' his niece Hannah.'
if true then
  verb = 'In the if'
end
puts 'After the if-then-end statement ' + verb

 输出发生了变化:

输出结果 写道
Dr. Cham sedated his niece Hannah.
Dr. Cham powdered his niece Hannah.
Dr. Cham electrocuted his niece Hannah.
testblock.rb:8: undefined local variable or method `verb' for main:Object (NameError)

 也就是说,那个block还是起了一些作用的。

也就是说,如果block意识到verb已经存在,然后就直接使用了。

小结:

  • 变量仍然有生存周期
  • block块 会去使用已经存在的同名的变量

 

有机会,我会好好研究下《Ruby Hacking Guide》,认真分析一下原因的。

谢谢各位朋友的提示,今天我将ruby升级到了1.9版。

ubuntu apt-get 写道
sudo apt-get install ruby1.9 irb1.9 rdoc1.9

 现在的系统环境

系统环境 写道
ruby 1.9.0 (2007-12-25 revision 14709) [i486-linux]

 现在重新运行一下看看结果:

运行结果 写道
Dr. Cham sedated his niece Hannah.
Dr. Cham powdered his niece Hannah.
Dr. Cham electrocuted his niece Hannah.
Yes, Dr. Cham rescued his niece Hannah.
After the if-then-end statement In the if

 确实已经恢复到期望输出了。

再次感谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值