Ruby Tips!

RubyのTipsを紹介します

モジュールを定義する

Rubyでモジュールを定義するには以下のようにする。

module モジュール名
  モジュールの内容
end

モジュールは他のクラスからincludeまたはextendして使用する。

module MyModule
  def hello_world
    puts 'Hello, World!'
  end
end

class MyClass1
  include MyModule
end

class MyClass2
  extend MyModule
end

myclass = MyClass1.new
myclass.hello_world #=> "Hello, World!"
MyClass2.hello_world #=> "Hello, World!"

汎用的な処理はモジュールとして定義しておくことで再利用性が高まる。