モノノフ日記

普通の日記です

Rubyのsuperの挙動

社内で下記コードの挙動どうなの?みたいな話題が挙がってました。

class A
  def foo
    bar
  end
  def bar
    puts "A's bar"
  end
end

class B < A
  def foo
    super
  end
  def bar
    puts "B's bar"
  end
end

# run
B.new.foo

出力結果は「B's bar」になります。http://codepad.org/T2LkPfc0
自分はA's barになるかな、と思ってたのでアレ?って感じ。
rubyのsuperはオーバーライドしたメソッドだけなんですね。
Javaだと「A's bar」になるそうです*1

PHPで試してみました。

<?php
class A
{
  public function foo() {
    $this->bar();
  }
  public function bar() {
    echo "A's bar";
  }
}

class B extends A
{
  public function foo() {
    parent::foo();
  }
  public function bar() {
    echo "B's bar";
  }
}

# run
$b = new B;
$b->foo();

結果は「B's bar」になります。http://codepad.org/HS534YeJ
これはthis使ってるからかな、となんとなく納得。ちなみにthisないとコンパイルが通りません。*2
結局rubyの場合もthis.barって意味になるから、phpと同じ挙動ってことになるのかな。

*1:会社の人が検証してた。自分は未検証。。

*2:codepadで