0
0

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.

【備忘録】Ruby : モジュールの使い方(Mix-in,多重継承)

0
Posted at
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 では単一継承を想定して作られているらしい。
# モジュールをミックスインすることで多重継承的な動きが可能


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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?