1.6
その他の機能
13
>>
a.x
=> 2
>>
a.x = 35
=> 35
>>
a + b
=> #<Point (45, 23)>
Struct.new
によって生成されたクラスは、この他にも便利な機能を持っています。たとえば、2
つの
Struct
が等しいかどうか確かめるため、属性を比較する等価メソッド
#==
が実装されています。
>>
Point.new(4, 5) == Point.new(4, 5)
=> true
>>
Point.new(4, 5) == Point.new(6, 7)
=> false
1.6.9
モンキーパッチング
いつでも既存のクラスやモジュールに新しいメソッドを追加することができます。これはモンキー
パッチング(monkey patching)と呼ばれ、既存のクラスの振る舞いを拡張できる強力な機能です。
>>
class Point
def -(other_point)
Point.new(x - other_point.x, y - other_point.y)
end
end
=> nil
>>
Point.new(10, 15) - Point.new(1, 1)
=> #<Point (9, 14)>
Rubyの組み込みクラスでさえ、モンキーパッチできます。
>>
class String
def shout
upcase + '!!!'
end
end
=> nil
>>
'hello world'.shout
=> "HELLO WORLD!!!"
1.6.10
定数の定義 ...