ruby实例方法和类方法




实例方法是类实例化后的对象使用的方法,类方法是不需要实例就可以调用的。如下:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值