Bye Bye Moore

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

Structにはメソッドを持たせる事ができる

shuzo-kino.hateblo.jp
でシレッと書きましたが、Structにはメソッドを与える事ができます。

これを使うと、
「そのクラス内でしか使わないけど、色々値の扱いが入り組んで面倒なデータ構造」を調子よくつかう事ができます。

たとえば、こんな感じ

Point = Struct.new(:x,:y) do
  def +(other_object)
    Point.new(x + other_object.x, y + other_object.y)
  end

  def ave
    ( ( x + y) /2).to_i
  end
end

a = Point.new(20,22)
b = Point.new(2,8)
(a+b).ave  #=> 26