32
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.

superを使って継承/Include/Extendしたメソッドをオーバーライド

Posted at

superは継承だけではなく、include, extendしたメソッドをオーバーライドした場合にも使えるということを知らなかったのでメモ。
ちなみにどのパターンもsuperを明示的に呼び出さなければ単なるメソッドの上書きになる。(PopCorn!!は出力されない)

super_include.rb
#!/usr/bin/env ruby

module Corn
  def pop
    puts 'PopCorn!!'
  end
end

class Caramel
  include Corn

  def pop
    super
    puts 'PopCaramelCorn!!'
  end

end

c = Caramel.new
c.pop
% ruby super_include.rb
PopCorn!!
PopCaramelCorn!!
super_extend.rb
#!/usr/bin/env ruby

module Corn
  def pop
    puts 'PopCorn!!'
  end
end

class Caramel
  extend Corn

  def self.pop
    super
    puts 'PopCaramelCorn!!'
  end

end

Caramel.pop
% ruby super_extend.rb
PopCorn!!
PopCaramelCorn!!
super_succeed.rb
#!/usr/bin/env ruby

class Corn
  def pop
    puts 'PopCorn!!'
  end
end

class Caramel < Corn
  def pop
    super
    puts 'PopCaramelCorn!!'
  end

end

c = Caramel.new
c.pop
% ruby super_succeed.rb
PopCorn!!
PopCaramelCorn!!

実行環境

% ruby -v
ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-linux]
32
26
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
32
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?