[Ruby笔记]26. self 不变,每一次调用函数都会产生新的local scope

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值