ruby静态方法

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

01#静态方法的4种写法
02class Test
03  def Test.StaticMethod1
04    puts "Test.StaticMethod1"
05  end
06   
07  def self.StaticMethod2
08    puts "Test.StaticMethod2"
09  end
10   
11  class << Test
12    def StaticMethod3
13      puts "Test.StaticMethod3"
14    end
15  end
16   
17  class << self
18    def StaticMethod4
19      puts "Test.StaticMethod4"
20    end
21  end
22end
23   
24Test.StaticMethod1
25Test.StaticMethod2
26Test.StaticMethod3
27Test.StaticMethod4

 

01#单例方法的2种写法
02 
03class Test
04  def method1
05    puts "method1"
06  end
07end
08 
09t1 = Test.new
10 
11def t1.singleMethod1
12  puts "t1.singleMethod1"
13end
14 
15class << t1
16  def singleMethod2
17    puts "t1.singleMethod2"
18  end
19end
20 
21t2 = Test.new
22 
23t1.method1
24t2.method1
25t1.singleMethod1
26t1.singleMethod2
27#t2.singleMethod1 #将报错
28#t2.singleMethod2 #将报错
原文地址:https://www.cnblogs.com/lexus/p/1887639.html