rubyのStruct
構造体型を使うと手軽に情報の入れ物ができる。
code:struct.rb
# シンプルな使い方
Database = Struct.new(:name, :host, :port, :user)
db = Database.new("production", "db.arai-ta.net", 3306, "arai-ta")
# メソッドを生やす場合
Database = Struct.new(:name, :host, :port, :user) do
def connection_string
# @host, @port のようには書けない。メソッド経由でアクセスする
"#{host}:#{port}"
end
end
# 継承してもいい
class Database < Struct.new(:name, :host, :port, :user)
def connection_string
"#{host}:#{port}"
end
end
なお、イミュータブルで値による比較をするDataクラスがruby 3.2で追加されている。