PerlerのRuby日記

Rubyとか

モジュールを継承したモジュールを作りたかった話

Hogeモジュールを継承したFugaモジュールを作ろうとしたらエラーになった。

module Hoge
  def self.hoge   # 特異メソッド
    puts "hoge!!!"
  end
end

module Fuga < Hoge
  def self.hoge   # 特異メソッド
    puts "fuga!!!"
    super
  end
end

Fuga.hoge
SyntaxError: (irb):7: syntax error, unexpected '<'
module Fuga < Hoge
             ^

文法上だめなんだ。知らなかった。


試行錯誤した結果。

module Hoge
  def hoge  # 普通のメソッドにして
    puts "hoge!!!"
  end
end

module Fuga
  extend Hoge   # extendして
  def self.hoge
    puts "fuga!!!"
    super   # superで呼ぶ
  end
end

Fuga.hoge

クラス継承の「<」をしていないのに「super」で呼んでしまえるところが気持ち悪い感じ。


単なるFugaの祖先は

1.9.3-p194 :026 > Fuga.ancestors
 => [Fuga] 

だけど、

中の特異クラスは

1.9.3-p194 :028 > class << Fuga
1.9.3-p194 :029?>   self
1.9.3-p194 :030?>   end.ancestors
 => [Hoge, Module, Object, Kernel, BasicObject] 

となっているので、モジュールメソッドとしてsuperが呼べるんだろうなあ。


というかモジュールの親子関係を作るときの正解はなんなんだろうか。