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

时间:2022-04-23
本文章向大家介绍ruby学习笔记(8)-"静态方法的4种写法"与"单例方法的2种写法",主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#静态方法的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 #将报错