ruby - 形状继承示例和 "The Ruby way"

标签 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

这是实现“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/

相关文章:

c++ - 这种回调的使用是惯用的吗?

java - Java中的命名参数习语

ruby - 邮件程序无法访问用户模型中的reset_token

c++ - 通过继承C++成为 friend

java - 每个类如何继承Object类?

c++ - 为什么 C++ 不允许继承友元?

node.js - Nodejs 在循环中等待

ruby - 如何在 Ruby 中调用方法作为参数?

ruby - 为什么不使用 `@messages`?

ruby-on-rails - 使用 ruby​​ 进行情感分析