实例方法是类实例化后的对象使用的方法,类方法是不需要实例就可以调用的。如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#encoding:utf-8
class
Apple
def
Apple.show
puts
"I am Apple.show"
puts
self
.
class
end
def
self
.show2
puts
"I am self.show2"
puts
self
.
class
end
def
show3
puts
"I am show3"
puts
self
.
class
end
end
apple = Apple.
new
Apple.show
Apple.show2
apple.show3
|
在类Apple中我们要加入类方法show和show2,需要再方法名前加上self或者Apple。当然,更推荐self。而实例方法show3前面没有加入self或者Apple。上面的代码的运行结果是
1
2
3
4
5
6
|
I am Apple.show
Class
I am self.show2
Class
I am show3
Apple
|
可以看到,类方法实际上是Class的实例的实例方法。在类中,类方法和实例方法中的self指向的对象是不同的。
如果使用下面的语句:
1
|
Apple.show3
|
会有以下报错:
1
|
in
`<
top
(required)>
': undefined method `show3'
for
Apple:Class (NoMethodError)
|
若有以下语句:
1
|
apple.show
|
会有以下报错:
1
|
in
`<
top
(required)>
': undefined method `show'
for
#<Apple:0x6cc550> (NoMethodError)
|
下面这种方式也能为Apple类添加类方法show:
1
2
3
4
5
6
7
8
9
10
11
12
|
#encoding:utf-8
class
Apple
end
def
Apple.show
puts
"I am Apple.show"
puts
self
.
class
end
apple = Apple.
new
Apple.show
|
以及:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#encoding:utf-8
class
Apple
end
class
<< Apple
def
Apple.show
puts
"I am Apple.show"
puts
self
.
class
end
end
apple = Apple.
new
Apple.show
|