1
0

More than 1 year has passed since last update.

superってなんだ?

Posted at

superとは親クラスの同名のメソッドを使えるようになるということです。
以下のコードではHogeクラスを親クラスにしてみる

class Hoge
  def hogehoge
    p 'ほげ!'
  end
end

class Huga < Hoge
  def hogehoge
    p 'ふがふがふが!'
  end
end

class Fuga < Hoge
  def hogehoge
    super
  end
end

Hugaにhogehogeメソッドを呼び出してみる

huga = Huga.new
huga.hogehoge
=> "ふがふがふが!"

親クラスのhogehogeメソッドはオーバーライド(上書き)されます

Fugaにhogehogeメソッドを呼び出してみる

fuga = Fuga.new
fuga.hogehoge
=> "ほげ!"

このように親クラスの同名のインスタンスメソッドを子クラスで使えるようになるもの。
それがsuperというものです。

短いですが以上です。何か間違いがございましたら、ご教示いただけますと幸いです。

【参考資料】

1
0
0

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
1
0