Ruby类函数定义的几种方式

Ruby类函数定义的几种方式 
参考: ruby-defining-class-methods 

1、 
Ruby代码   收藏代码
  1. class Person  
  2.   def Person.find(id)  
  3.     ...  
  4.   end  
  5. end  

这种方式,有一点不好,如果更改类名,相应的类函数定义的类名也要更改。 
2、
Ruby代码   收藏代码
  1. class Person  
  2.   def self.find(id)  
  3.     ...  
  4.   end  
  5. end  

这种方式比较好,没有上面提到的问题。作者也推荐使用这种方式。 
3、 
Ruby代码   收藏代码
  1. class Person  
  2.   class << self  
  3.     protected  
  4.     def find(id)  
  5.       ...  
  6.     end  
  7.   end  
  8. end  

在定义protected类函数时使用。为什么要定义protected类函数可参见作者的另一篇文章 Protected Class Methods。 
4、比较复杂的 
Ruby代码   收藏代码
  1. class Object # http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html  
  2.   def meta_def name, &blk  
  3.     (class << selfselfend).instance_eval { define_method name, &blk }  
  4.   end  
  5. end  
  6.   
  7. class Service  
  8.   def self.responses(hash)  
  9.     hash.each do |method_name, result|  
  10.       meta_def method_name do  
  11.         result  
  12.       end  
  13.     end  
  14.   end  
  15.     
  16.   responses :success => 20, :unreachable => 23  
  17. end  
  18.   
  19. Service.success # => 20  
  20. Service.unreachable # => 23  

由于本人Ruby功力还不够,上面的代码有些还看不明,有兴趣的读者可直接看原文。 
5、最后作者还提到一种方式 
Ruby代码   收藏代码
  1. class Person  
  2.   instance_eval do  
  3.     def find(id)  
  4.       ...  
  5.     end  
  6.   end  
  7. end  

用到instance_eval,没搞清楚这种方式有什么特点。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值