按照我们一般的思维模式,特别是在大量使用了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
确实已经恢复到期望输出了。
再次感谢。