为圈子创建 class,ruby

Creating class for circle, ruby

这是我关于通过 classes 创建几何形状的第二个问题。

所以,我想创建一个圈子。

  1. 首先我创建一个class点
  2. 然后 - 创建一条 class 线,使用两个点(这将是我们的直径)
  3. 现在我们要计算这两个点之间的距离(直径)
  4. 然后我们创建class圈
  5. 并使用直径创建一个圆

希望,到目前为止一切顺利。但是当我开始编码时,我遇到了一些麻烦。

正在创建 class 点:

class Point
  attr_accessor :x, :y
  def initialize
    @x = 10
    @y = 10
  end
end

然后,class行:

class Line
  attr_accessor :p1, :p2
  def initialize
    @p1 = Point.new
    @p2 = Point.new
  end
  def distance
    @distance = Math::sqrt((@p2.x - @p1.x) ** 2 + (@p2.y - @p1.y) ** 2) # -> rb.16
  end
end

在第 class 行开始出现问题。如您所知,我想定义方法来计算直线 class 中各点之间的距离。感谢google搜索计算公式为:

平方根来自 ((point_2.x - point_1.x)**2 + (point_2.y - point_1.y)**2)

#points
point_01 = Point.new
point_01.x = 20
point_02 = Point.new
point_02.x = 10

#line
d = Line.new
d.p1 = point_01
d.p2 = point_02
dis = d.distance # -> rb.40
print dis

但它给我一个错误:

rb:16:in `distance': wrong number of arguments (1 for 0) (ArgumentError)

rb:40: in `<top (required)>'
    from -e:1:in `load'
    from -e:1:in `<main>'

这是什么错误,它们是什么意思?

下一步将计算周长 (C),公式为:

C = Pi * 直径

对吗?

class Circle
  attr_accessor :diametr, :c
  def initialize
    @diametr = Line.new
  end
  def circle_length
    return @c = @diametr * Math::PI
  end
end
#circle
circle = Circle.new
circle.diametr = d
res = circle.circle_length

请注意,我只是在学习,这可能是一个愚蠢的问题,但我仍然不明白。

感谢您的帮助!

是的,谢谢下面的评论,在使用公式计算周长后,错误出现Circle class。你能帮我吗?

我 运行 你的代码,但我没有收到 rb:16:in distance': wrong number of arguments (1 for 0) (ArgumentError) 错误。

circle_length 方法确实会抛出错误,这是因为您正在尝试乘以 @diameter,它是 Line 的一个实例。

为此,您需要为 Line 实施 *:

class Line
  def *(other)
    distance * other
  end
end

关于这里发生的事情的进一步解释:

* 与 ruby 中的任何其他方法一样,具有一些特殊的语法。当您执行 4 * 5 时,您是在 4 上调用 * 方法(这只是另一个 ruby 对象,Integer 的一个实例),并传递5 作为参数。上面的代码implements/defines一个方法* for Line,本质上Integer同样实现了方法*

它接受一个数字作为参数,returns distance 方法的结果乘以参数的结果。