由以下範例, 就可以知道 self 的用法與差異了.
irb(main):060:0> class TestSelf
irb(main):061:1> def m
irb(main):062:2> puts '123'
irb(main):063:2> end
irb(main):064:1> def self.mm
irb(main):065:2> puts '456'
irb(main):066:2> end
irb(main):067:1> end
=> nil
irb(main):068:0> a = TestSelf.new
=> #
irb(main):069:0> a.m
123
=> nil
irb(main):070:0> a.mm # self 不能用
NoMethodError: undefined method `mm' for #
from (irb):70
irb(main):071:0> TestSelf::mm #self 可以用
456
=> nil
irb(main):072:0> TestSelf::m
NoMethodError: undefined method `m' for TestSelf:Class
from (irb):72
irb(main):073:0> TestSelf.m
NoMethodError: undefined method `m' for TestSelf:Class
from (irb):73
這邊也有更深入的解釋: http://ilstar.blogbus.com/logs/59782933.html
沒有留言:
張貼留言