クラスメソッド

Rubyのクラスメソッドは、クラスオブジェクトの特異メソッドです。

class Rubyco
  def self.hello
    puts "Hello!"
  end
end

Rubyco.hello        #=> Hello!

こう書くこともできます。

class Rubyco
end

def Rubyco.hello
  puts "Hello!"
end

Rubyco.hello        #=> Hello!

クラスオブジェクトも、普通のオブジェクトですから、これでもよいですね。

class Rubyco
end

klass = Rubyco

def klass.hello
  puts "Hello!"
end

Rubyco.hello        #=> Hello!

インスタンスに対する特異メソッドと違うのは、サブクラスに継承されることです。

class Rubyco
end

klass = Rubyco

def klass.hello
  puts "Hello!"
end

class Child < Rubyco
end

Child.hello     #=> Hello!