疑問:シングルトンメソッドのaliasはどうする?→解決:特異クラスを使う

Rubyco.helloをRubyco.xxx_helloとして呼ぶようなaliasを作るときにはどうすればよいのでしょう?

class Rubyco
  def self.hello
    puts "Hello"
  end
  alias :xxx_hello :hello # undefined method `hello' for class `Rubyco'
end

追記:kjanaさんに教えていただきました。ありがとうございます。なるほど!特異クラスを使えばよいのですね。ええと、Rubycoをインスタンスとするクラスオブジェクトに触るという感じですか。

class Rubyco
  def self.hello
    puts "Hello"
  end
  class <<self
    alias :original_hello :hello
  end
end

Rubyco.original_hello #=> Hello

selfの変遷を調べてみましょう。Rubyはこういうとき便利ですね。クラス定義の途中でエヴァれるなんて。

puts self             #=> main

class Rubyco
  puts self           #=> Rubyco

  def self.hello
    puts "Hello"
  end

  class <<self
    puts self         #=> #<Class:Rubyco>
    alias :original_hello :hello
  end
end

追記:上のselfの変遷を見ていると、以下のようにも書けることはすぐに理解できます。要は、メソッド定義や(特異)クラス定義を外側に出してselfの部分にRubycoを入れたわけです。

class Rubyco
end

def Rubyco.hello
  puts "Hello"
end

class <<Rubyco
  alias :original_hello :hello
end

Rubyco.original_hello   #=> Hello