在我从十年的 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
这是实现“The Ruby Way”吗?如果没有,您将如何实现?
最佳答案
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))
这是一个称为鸭子类型的功能。只要 twod 有 area 方法(用 Ruby 的说法,我们会说 twod 响应 area),你就可以开始了。
关于ruby - 形状继承示例和 "The Ruby way",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1077508/