class and instance methods in ruby

类方法是一个类的单件方法,可以被继承。类方法是单件方法的特例。

单件方法定义

def obj.a_singleton_method
end

类方法定义

Way 1

class Foo
  def self.bar
    puts 'class method'
  end
end

Foo.bar # "class method"

Way 2

class Foo
  class << self
    def bar
      puts 'class method'
    end
  end
end

Foo.bar # "class method"

Way 3

class Foo; end
def Foo.bar
  puts 'class method'
end

Foo.bar # "class method"

http://www.railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

相关文章: