Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

Structで構造体なデータを扱う

StructはRubyで構造体なクラスを扱うときに使えます。
使い方がちょいと特殊です。

class Point < Struct.new(:x, :y)
  def +(other_object)
    Point.new(x + other_object.x, y + other_object.y)
  end  
end  
=> :inspect

a = Point.new(1,3)
#=> #<struct Point x=1, y=3>

b = Point.new(5,11)
#=> #<struct Point x=5, y=11>

a + b
#=> #<struct Point x=6, y=14>

a.x
#=> 1

a.y
#=> 3

変数の代入もこの通り

a.x = 34
#=> 34

a
#=> #<struct Point x=34, y=3>

参考もと