nat*_*han 3 ruby inheritance idioms
在我从十年的C++过渡到Ruby的过程中,我发现自己第二次猜测如何完成最简单的事情.鉴于下面的经典形状推导示例,我想知道这是否是"The Ruby Way".虽然我相信下面的代码没有任何本质上的错误,但我仍然觉得我没有充分利用Ruby的全部功能.
class Shape
def initialize
end
end
class TwoD < Shape
def initialize
super()
end
def area
return 0.0
end
end
class Square < TwoD
def initialize( side )
super()
@side = side
end
def area
return @side * @side
end
end
def shapeArea( twod )
puts twod.area
end
square = Square.new( 2 )
shapeArea( square ) # => 4
Run Code Online (Sandbox Code Playgroud)
这是实施"红宝石之路"吗?如果没有,你会如何实现这个?
关于Ruby的美妙之处在于,您不必仅使用继承来提供已实现方法的契约.相反,你可以做到这一点:
class Square
def initialize(side)
@side = side
end
def area
@side * @side
end
end
class Circle
def initialize(radius)
@radius = radius
end
def area
@radius * @radius * 3.14159
end
end
shapeArea(Square.new(2))
shapeArea(Circle.new(5))
Run Code Online (Sandbox Code Playgroud)
这是一种称为鸭子打字的功能.只要twod有一个区域方法(用Ruby的说法,我们会说twod响应区域),你很高兴.
| 归档时间: |
|
| 查看次数: |
1219 次 |
| 最近记录: |