ruby学习笔记(8)-"静态方法的4种写法"与"单例方法的2种写法"

时间:2021-03-23 19:32:49
#静态方法的4种写法
class Test
  def Test.StaticMethod1
    puts "Test.StaticMethod1"
  end
  
  def self.StaticMethod2
    puts "Test.StaticMethod2"
  end
  
  class << Test
    def StaticMethod3
      puts "Test.StaticMethod3"
    end
  end
  
  class << self
    def StaticMethod4
      puts "Test.StaticMethod4"
    end
  end
end
  
Test.StaticMethod1
Test.StaticMethod2
Test.StaticMethod3
Test.StaticMethod4

 

#单例方法的2种写法

class Test
  def method1
    puts "method1"
  end
end

t1 = Test.new

def t1.singleMethod1
  puts "t1.singleMethod1"
end

class << t1
  def singleMethod2
    puts "t1.singleMethod2"
  end
end

t2 = Test.new

t1.method1
t2.method1
t1.singleMethod1
t1.singleMethod2
#t2.singleMethod1 #将报错
#t2.singleMethod2 #将报错