「Crystal」の版間の差分
削除された内容 追加された内容
→包含と継承: 「Crystalらしいコード」に変更 タグ: 2017年版ソースエディター |
→包含と継承: 冗長な p メソッドを整理、inspect メソッドを実装。 タグ: 2017年版ソースエディター |
||
403 行
;包含と継承:<syntaxhighlight lang=crystal line>
class Point
def initialize(@x = 0, @y = 0) end
def inspect(io) io << "x:#{@x}, y:#{@y}" end
end▼
def move(dx = 0, dy = 0)
@x, @y = @x + dx, @y + dy
self
end
416 ⟶ 414行目:
def initialize(x = 0, y = 0)
@location = Point.new(x, y)
end
def inspect(io) @location.inspect(io) end
def move(x, y)
@location.move(x, y)
self
end
428 ⟶ 425行目:
def initialize(x = 0, y = 0, @width = 0, @height = 0)
super(x, y)
▲ end
def inspect(io)
super(io)
io << ", width:#{@width}, height:#{@height}"
end
end
rct = Rectangle.new(12, 32, 100, 50)
p!
rct.move(11, 21)
</syntaxhighlight>
;実行結果:<syntaxhighlight lang=text>
rct # => x:12, y:32, width:100, height:50
rct.is_a?(Rectangle) # => true ▼
rct.is_a?(Shape) # => true ▼
rct.is_a?(Point) # => false ▼
rct.move(11, 21)
▲rct.is_a?(Rectangle) # => true
▲rct.is_a?(Shape) # => true
▲rct.is_a?(Point) # => false
</syntaxhighlight>
|