读书人

Ruby类函数定义的几种形式

发布时间: 2012-08-21 13:00:21 作者: rapoo

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

1、

class Person  def Person.find(id)    ...  endend

这种方式,有一点不好,如果更改类名,相应的类函数定义的类名也要更改。
2、
class Person  def self.find(id)    ...  endend

这种方式比较好,没有上面提到的问题。作者也推荐使用这种方式。
3、
class Person  class << self    protected    def find(id)      ...    end  endend

在定义protected类函数时使用。为什么要定义protected类函数可参见作者的另一篇文章Protected Class Methods。
4、比较复杂的
class Object # http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html  def meta_def name, &blk    (class << self; self; end).instance_eval { define_method name, &blk }  endendclass Service  def self.responses(hash)    hash.each do |method_name, result|      meta_def method_name do        result      end    end  end    responses :success => 20, :unreachable => 23endService.success # => 20Service.unreachable # => 23

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

用到instance_eval,没搞清楚这种方式有什么特点。

读书人网 >Ruby Rails

热点推荐