【发布时间】:2017-05-29 19:06:46
【问题描述】:
我有以下代码:
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>'
请判断整个代码是否只是垃圾。
【问题讨论】:
-
你没有显示你打电话给
.new的地方。另外,你调用的type方法是什么? -
该错误究竟是在哪里(文件名和行号)引发的?您如何尝试初始化实例?
type是如何定义的? -
在那里,我尽可能多地澄清。如果问题太长,我很抱歉。
-
“如果整个代码只是垃圾,请告诉我” - 代码,ahem,没有完全遵守ruby style guidelines。但你几乎让它工作了。这才是最重要的。
-
另外,友好的建议:学习如何调试和调查问题。这是程序员可以拥有的最重要的技能之一。在您的情况下,错误消息直接指向一行代码。这是您应该首先看到的。
标签: ruby