我有以下代码:
load 'Point.rb'
class Triangle
def initialize(x, y , z)
if !x.is_a?(Point) || !y.is_a?(Point) || !z.is_a?(Point)
puts "Invalid data, a Triangle can only be initialized through points"
else
@x=x
@y=y
@z=z
@type=type(x, y, z)
end
end
def type(x, y, z)
if x.distance(y) == y.distance(z) && y.distance(z) == z.distance(x)
return "equilateral"
elsif x.distance(y)== y.distance(z) || y.distance(z) == z.distance(x) || z.distance(x) == x.distance(y)
return "isosceles"
else
return "scalene"
end
end
attr_accessor :type
end
我正在调用这样的方法:
load 'Triangle.rb'
x=Point.new(0,0)
y=Point.new(1,1)
z=Point.new(2,0)
triangle=Triangle.new x, y, z
puts triangle.type
班级Point
如下:
class Point
def initialize (x=0, y=0)
@x=x.to_i
@y=y.to_i
end
def ==(point)
if @x==point.x && @y==point.y
return true
else
return false
end
end
def distance(point)
Math.hypot((@x-point.x),(@y-point.y))
end
attr_accessor :y
attr_accessor :x
end
错误如下:
Triangle.rb:11:in `initialize': wrong number of arguments (given 3, expected 0) (ArgumentError)
from Triangle_test.rb:6:in `new'
from Triangle_test.rb:6:in `<main>'
请告诉整个代码是否只是垃圾。
答案 0 :(得分:2)
在Triangle
课程中,你有方法type
接受三个参数,然后在下面你有attr_accessor :type
用无参数的getter覆盖那个3参数方法。
这就是你在初始化程序中执行此操作时出现错误的原因
@type=type(x, y, z)
答案 1 :(得分:1)
以下是代码的清理版本:
calculate_type
方法attr_accessor
替换为attr_reader
x,y,z
重命名a,b,c
以避免坐标和点之间的混淆class Point
attr_reader :x, :y
def initialize(x = 0, y = 0)
@x = x.to_i
@y = y.to_i
end
def ==(point)
@x == point.x && @y == point.y
end
def distance(point)
Math.hypot((@x - point.x), (@y - point.y))
end
end
class Triangle
attr_reader :a, :b, :c, :type
def initialize(a, b, c)
raise 'Invalid data, a Triangle can only be initialized through points' unless [a, b, c].all? { |p| p.is_a?(Point) }
@a, @b, @c = a, b, c
@type = calculate_type
end
private
def calculate_type
if a.distance(b) == b.distance(c) && b.distance(c) == c.distance(a)
'equilateral'
elsif a.distance(b) == b.distance(c) || b.distance(c) == c.distance(a) || c.distance(a) == a.distance(b)
'isosceles'
else
'scalene'
end
end
end
a = Point.new(0, 0)
b = Point.new(1, 1)
c = Point.new(2, 0)
triangle = Triangle.new a, b, c
puts triangle.type
# isosceles