7
5

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のmodule と classの違い

Last updated at Posted at 2017-04-03

#はじめに
同じ実行例で
Rubyのclassとmoduleの具体的な使い分けの説明 の メモ

#moduleの使用例
moduleで定義したメソッドの使い方

module.rb
# -*- coding: utf-8 -*-
#moduleとメソッドの作成
module Print_m
  def hello_m
    "hello"
  end

  def world_m
    "world"
  end

  def module_m
     "module"
  end
end

if __FILE__ == $0
 #モジュールをインストール
  include Print_m

 # モジュール.メソッド で実行
  puts hello_m
  puts world_m
  puts module_m
end
> ruby module.rb
hello
world
module

#classの使用例
classで定義したメソッドの使い方

class.rb
# -*- coding: utf-8 -*-

class Print_class
  def hello_c
    "hello"
  end

  def world_c
    "world"
  end
end

if __FILE__ == $0
  print_c = Print_class.new
  puts print_c.hello_c
  puts print_c.world_c
end

>ruby class.rb
hello
world

#module とclassの実行方法の違い
##moduleの実行方法

module.rb
include moduleName
method

##classの実行方法

class.rb
class = className.new
class.method

#具体的な違い!
##classにmoduleを呼べるが、moduleからclassを呼べない!!

###classからmoduleを呼ぶ例

module2class.rb
# -*- coding: utf-8 -*-
module Print
  def hello_m
    "hello"
  end
  def world_m
    "world"
  end
  def modulePrint_m
    "modulePrint"
  end
end

class Print_class
  include Print

  def hello_c
    hello_m
  end

  def world_c
    world_m
  end
end

if __FILE__ == $0
  print_c = Print_class.new
  puts print_c.hello_c
  puts print_c.world_c
  puts print_c.modulePrint_m
end

class.new を実行すると
classのなかで、moduleをインクルードしているので
class.モジュールのメソッド が使用できる

7
5
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?