LoginSignup
1
1

More than 3 years have passed since last update.

Rubyでsuperなメソッドが定義されているかを調べる

Posted at

タイトルまんまなんで早速本題

本題

class Foo
  def hoge
    super if defined?(super) # これより上で`hoge`が定義されているかは不明
    puts :foo
  end
end

class Bar < Foo
  def hoge
    super # Fooで`hoge`が定義されているのは知ってるからここはそのままsuper
    puts :bar
  end
end

Bar.new.hoge # => "bar\nfoo\n"

super if defined?(super)がキモ。言われてみればそのままだけど、なかなか思いつかなかった。

参考資料

ぶっちゃけ、ここで見たことを書き写したようなもんです。

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