40
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

親クラスの別のメソッドを呼ぶ

Last updated at Posted at 2015-03-13

やりたいこと

子クラスのメソッド bar から親クラスのメソッド foo を呼びたい。
オーバーライドしたメソッドではないので super が使えない。

class Parent
  def foo
    puts 'parent'
  end
end

class Child < Parent
  def foo
    puts 'child'
  end

  def bar
    # ここで親の #foo を呼びたい
  end
end

alias を使う

上書きする前に alias しておけばよい

class Parent
  def foo
    puts 'parent'
  end
end

class Child < Parent
  alias :super_foo :foo

  def foo
    puts 'child'
  end

  def bar
    super_foo #=> parent
  end
end

self.class.superclass からメソッドを取り出して bind して使う

これでもできる

class Parent
  def foo
    puts 'parent'
  end
end

class Child < Parent
  def super_foo(*args, &blk)
    self.class.superclass.instance_method(:foo).bind(self).call(*args, &blk)
  end

  def foo
    puts 'child'
  end

  def bar
    super_foo #=> parent
  end
end

super_method を使う (Ruby >= 2.2)

コメントより(thanks!)。Ruby >= 2.2 なら super_method を利用できる。

class Parent
  def foo
    puts 'parent'
  end
end

class Child < Parent
  def foo
    puts 'child'
  end

  def bar
    public_method(:foo).super_method.call #=> parent
  end
end
40
26
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?