Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

やりたいこと

子クラスのメソッド 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
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away