Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
4
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

Organization

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

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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
4
Help us understand the problem. What are the problem?