[Ruby笔记]23.Ruby self “main class module instance”

self !

  • test_self.rb
puts "Top Level"
puts "self is #{self}" # self is main

class C
    puts "Class definition block : "
    puts "self is #{self}" #self is C

    # class method
    def self.x
        puts "Class method C.x : "
        puts "self is #{self}" #self is C
    end

    # instance method
    def m
        puts "Instance method C%m : "
        puts "self is #{self}" #self is #<C:0x00000002a49320>
    end
end

C.x

c = C.new
c.m


  • output
C:\Users\Administrator\RubyCode>ruby test_self.rb
Top Level
self is main

Class definition block :
self is C

Class method C.x :
self is C

Instance method C%m :
self is #<C:0x00000002a09018>

self ?

  • 默认是main
  • class C里面的就是 C
  • module M里面就是M
  • class method 也是 C
  • instance method那么就是对象obj

reference

《The Well-Grounded Rubyist, Second Edition》
(https://www.manning.com/books/the-well-grounded-rubyist-second-edition)
5.1.3. Self inside class, module, and method definitions

    ◯
   ┏╋┛
    ┣┓
≡= ━┛┃
http://emoji.vis.ne.jp/nigero5.htm
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值