ruby学习笔记(8)-"静态方法的4种写法"与"单例方法的2种写法"
01 | #静态方法的4种写法 |
02 | class 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 |
22 | end |
23 | |
24 | Test.StaticMethod1 |
25 | Test.StaticMethod2 |
26 | Test.StaticMethod3 |
27 | Test.StaticMethod4 |
01 | #单例方法的2种写法 |
02 |
03 | class Test |
04 | def method1 |
05 | puts "method1" |
06 | end |
07 | end |
08 |
09 | t1 = Test. new |
10 |
11 | def t1.singleMethod1 |
12 | puts "t1.singleMethod1" |
13 | end |
14 |
15 | class << t1 |
16 | def singleMethod2 |
17 | puts "t1.singleMethod2" |
18 | end |
19 | end |
20 |
21 | t2 = Test. new |
22 |
23 | t1.method1 |
24 | t2.method1 |
25 | t1.singleMethod1 |
26 | t1.singleMethod2 |
27 | #t2.singleMethod1 #将报错 |
28 | #t2.singleMethod2 #将报错 |