LoginSignup
3
0

【Ruby Gold3.1詰まったシリーズ】superでのメソッド呼出し

Last updated at Posted at 2023-12-04

はじめに

今回はsuperに関する内容です。superではスーパークラスのメソッドのみ呼び出すと理解していましたがそうではないらしいです。

irbで確認してみた

環境はruby2.5.3です。
まず、SuperClsを継承したSubClsを作成し実行する。

class SuperCls
  def hoge
    puts "SuperCls"
  end
end

class SubCls < SuperCls
  def hoge
    puts "SubCls"
    super
  end
end

hogeメソッドを呼び出すと、

irb(main):013:0> SubCls.new.hoge
SubCls
SuperCls

SubClsとSuperClsが表示され、同名メソッドを呼び出せました。

次に、ModモジュールをmixinしたClsを作成し実行する。

module Mod
  def hoge
    puts "Mod"
  end
end

class Cls
  include Mod
  def hoge
    puts "Cls"
    super
  end
end

hogeメソッドを呼び出すと、

irb(main):014:0> Cls.new.hoge
Cls
Mod

ClsとModが表示され、同名メソッドを呼び出せました。

おわりに

確認した結果、superではスーパークラスだけではなくmixinしたモジュールの同名メソッドも呼び出せることが分かりました。もし誤っていたらご指摘いただけると助かります!

参考

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