[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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章