削除された内容 追加された内容
Ef3 (トーク | 投稿記録)
→‎包含と継承: 「Crystalらしいコード」に変更
タグ: 2017年版ソースエディター
Ef3 (トーク | 投稿記録)
→‎包含と継承: 冗長な 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
p("Point::initialize")
end
def move(dx = 0, dy = 0)
@x, @y = @x + dx, @y + dy
p("Point::move")
self
end
416 ⟶ 414行目:
def initialize(x = 0, y = 0)
@location = Point.new(x, y)
p("Shape::initialize")
end
def inspect(io) @location.inspect(io) end
def move(x, y)
@location.move(x, y)
p("Shape::move")
self
end
428 ⟶ 425行目:
def initialize(x = 0, y = 0, @width = 0, @height = 0)
super(x, y)
end
p("Rectangle::initialize")
def inspect(io)
super(io)
io << ", width:#{@width}, height:#{@height}"
end
end
 
p("Create a Rectangle!")
rct = Rectangle.new(12, 32, 100, 50)
p! rct,
p! rct.is_a?( Rectangle ),
p! rct.is_a?( Shape ),
p! rct.is_a?( Point ),
rct.move(11, 21)
p! rct
rct2 = Rectangle.new(1, 2, 10, 150)
p! rct, rct2
</syntaxhighlight>
;実行結果:<syntaxhighlight lang=text>
rct # => x:12, y:32, width:100, height:50
"Create a Rectangle!"
rct.is_a?(Rectangle) # => true
"Point::initialize"
rct.is_a?(Shape) # => true
"Shape::initialize"
rct.is_a?(Point) # => false
"Rectangle::initialize"
rct.move(11, 21) # => #<Rectangle:0x80096ee40 @location=#<Point:0x80096fe60> @x=12:23, @y=32>:53, @width=:100, @height=:50>
rct.is_a?(Rectangle) # => true
rct.is_a?(Shape) # => true
rct.is_a?(Point) # => false
"Point::move"
"Shape::move"
rct # => #<Rectangle:0x80096ee40 @location=#<Point:0x80096fe60 @x=23, @y=53>, @width=100, @height=50>
"Point::initialize"
"Shape::initialize"
"Rectangle::initialize"
rct # => #<Rectangle:0x80096ee40 @location=#<Point:0x80096fe60 @x=23, @y=53>, @width=100, @height=50>
rct2 # => #<Rectangle:0x80096ee20 @location=#<Point:0x80096fe50 @x=1, @y=2>, @width=10, @height=150>
</syntaxhighlight>