code
# File : ex.rb
class C
def hello(a, recurse = false)
print "Now , self is : "
p self
print "self object id is : "
p self.object_id
print "And here's a : "
puts a
print "a has object id : "
p a.object_id
puts ""
if recurse
puts "Calling myself (recurse) ... "
puts
hello("2nd value")
puts
print "Back after recursion ; here's a : "
puts a
print "a has object id : "
p a.object_id
end
end
end
c = C.new
c.hello("1st",true)
note
- 递归函数
hello()
,当第二个参数为true
时进入if
语句调用自身; self
的确没变,在这次运行中都显示self is : #<C:0x00000002b98c80>
;- 很明显,每一次调用
hello()
,变量a
都发生了变化,第一次是1st
,第二次是2nd
; - 无论是直接
p self
输出,还是输出self.object_id
都可以观察到递归中self
是不变的。
run
PS C:\Users\Administrator\RubyCode> ruby ex.rb
Now , self is : #<C:0x00000002b98c80>
self object id is : 22857280
And here's a : 1st
a has object id : 22857260
Calling myself (recurse) ...
Now , self is : #<C:0x00000002b98c80>
self object id is : 22857280
And here's a : 2nd value
a has object id : 22856860
Back after recursion ; here's a : 1st
a has object id : 22857260
reference
《The Well-Grounded Rubyist, Second Edition》
(https://www.manning.com/books/the-well-grounded-rubyist-second-edition)
5.2.3. The interaction between local scope and self
眠いよ・・・
/ヽ、
/__ヾ
~(ηω=)ノ
~( ×)
∪∪
http://emoji.vis.ne.jp/neruyo_3koma1.htm