LoginSignup
7
4

More than 5 years have passed since last update.

[Ruby]Struct, OpenStructクラスのメソッド

Posted at

1年くらい前にRubyの勉強のためにStruct, OpenStructクラスの便利メソッドをまとめたもの

参考
パーフェクトRuby
https://docs.ruby-lang.org/ja/latest/class/Struct.html
https://docs.ruby-lang.org/ja/latest/class/OpenStruct.html

Struct

構造体クラス

基本的な使い方

Structのサブクラスを作って利用する。

point = Struct.new('Point', :x, :y) # => Struct::Point
item = point.new(10, 30) # => #<struct Struct::Point x=10, y=30>

p item.x # => 10

メソッド定義

Struct.newにブロックを渡し、その中にインスタンスメソッドを定義する。

Human = Struct.new('Human', :age, :gender) do
  def teen?
    (13..19).include?(age)
  end
end

Human.new(17).teen? # => true

OpenStruct

要素を動的に追加・削除できる手軽な構造体を提供するクラス

require 'ostruct'

Human = OpenStruct.new
Human.gender = 'male'

p Human.gender # => "male"

初期値にHashを使用することもできる。

require 'ostruct'

Son = OpenStruct.new({gender: :male})
p Son.gender # => :male
7
4
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
7
4