RSS

タグ別アーカイブ: include

Crystal: モジュール

モジュールとは module キーワードで囲まれたブロックであり、次の用途のため作成する。

  • 名前空間として
  • 他のブロック (class, module) の内容の一部として

名前空間として使う例を下に示す。

module Curses
  class Window
  end
end

Curses::Window.new

クラスの一部として使う例を下に示す。

module ItemsSize
  def size
    items.size
  end
end

class Items
  include ItemsSize

  def items
    [1, 2, 3]
  end
end

items = Items.new
items.size # => 3

include でなく extend を使ってモジュールをクラスや他のモジュールに含める場合は、そのモジュールのメソッドをクラスメソッドとして使用できる。

module SomeSize
  def size
    3
  end
end

class Items
  extend SomeSize
end

Items.size # => 3

extend に self を指定すると、そのモジュールのメソッドを公開できる。

module Base64
  extend self

  def encode64(string)
    # ...
  end

  def decode64(string)
    # ...
  end
end

この Base64 のメソッドは次のように使用できる。

Base64.encode(“abc”)

 
コメントする

投稿者: : 2023/11/20 投稿先 Crystal

 

タグ: , ,