Andrey Drozdov Andrey Drozdov - 6 months ago 9
Ruby Question

Creating class for circle, ruby

It's my second question about creating geometric shapes via classes.

So, I want to create a circle.


  1. First of all I create a class Point

  2. Then - create a class Line, using two points (this will be our diameter)

  3. Now we have to calculate the distance between this points (diameter)

  4. Then we create class Circle

  5. And using diameter to create a circle



Hope, so far so good. But when i get to coding i meat some troubles.

Creating class Point:

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


Then, class Line:

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


And in Line class the problems starts. As you understand I want to define method to calculate distance between points in the Line class. Thnx to google search the formula for calculating is:

square root from ((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


But it puts me an error:

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>'


What are this errors, what they mean?

And the next step will be to calculate circumference (C) with formula:

C = Pi * Diameter

Is that right?

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


Please note that I'm only studying and it may be a silly question but still I don't understand it.

Thank for your help!

Yeah, thnx to the comment below, the error appears Circle class, after using formula to calculate circumference. can you help me with this.

Answer

I ran your code and I'm not getting the rb:16:in distance': wrong number of arguments (1 for 0) (ArgumentError) error.

The circle_length method does throw an error and it's because you are trying to multiply @diameter, which is an instance of Line.

You need to implement *, which is really just a method, for Line:

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