sample.rb
module ActionTarget
# モジュール
def throw
puts "#{@person}は#{@object}を投げた"
end
def kick
puts "#{@person}は#{@object}を蹴った"
end
end
class ActionPlace
# 継承元クラス
def run
puts "#{@person}は#{@place}で走った"
end
def sleep
puts "#{@person}は#{@place}で寝た"
end
end
class Person < ActionPlace
# クラスを継承
include ActionTarget
# モジュールのメソッドが使えるようにミックスイン
attr_accessor :object,:place,:person
def initialize(object,place)
@object = object
@place = place
@person = "私"
end
end
me = Person.new("サッカーボール","校庭")
me.throw # (モジュールメソッド) =>私はサッカーボールを投げた
me.kick # (モジュールメソッド) =>私はサッカーボールを蹴った
me.run # (継承クラスのインスタンスメソッド) =>私は校庭で走った
me.sleep # (継承クラスのインスタンスメソッド) =>私は校庭で寝た
# ruby では単一継承を想定して作られているらしい。
# モジュールをミックスインすることで多重継承的な動きが可能