よたらぼ
自分の興味の赴くままにIT技術系のネタを取りとめもなくメモっています。
Ruby言語やLinuxのネタが多いです。

September 19, 2008 [おもひで]

[Ruby] 継承+エイリアスのハマりどころ

前もハマったような気がするが・・・・。

class Test
  def initialize
    hello
    foo
  end
  def hello; p "test1"; end
  alias :foo :hello
end
 
class Test2 < Test
  def hello; p "test2"; end
end
 
Test2.new

この時、Test2.newの結果はどうなるか。
× test2(改行)test2
○ test2(改行)test1

Test2でもfooメソッドをhelloの結果と同じにしたい場合はTest2で改めてエイリアスする必要がある。こんな感じ。

class Test3 < Test
  def hello; p "test3"; end
  alias :foo :hello
end
 
Test3.new

サブクラスでfooを呼び出すと、サブクラスのhelloを呼んでほしい場合は、素直にfooをメソッドとして定義すればよい。

class Test
  def initialize
    hello
    foo
  end
  def hello; p "test1"; end
  def foo; hello; end
end
 
class Test2 < Test
  def hello; p "test2"; end
end
 
Test2.new

この場合は、どちらもtest2を返す。

以下のような使い方を基準に考えると不思議ではないかもしれないんだけど、クラスの継承を基準にaliasを使うとなぜだかハマってしまう。こはいかに。

def hello
  p "hello"
end
 
alias :hello_org :hello
 
def hello
  hello_org
  p "hello2"
end
 
hello 


編集