我是一个ruby新手,正在做一个全栈的web开发人员课程@ Bloc.io,我在以下方面遇到了问题……
“我们应该能够对每个形状调用larger_than?方法。此方法应计算两个形状并根据一个形状的面积大于另一个形状的面积返回true或false。换句话说,如果接收对象大于参数对象,则larger_than?方法应返回true:
square.larger_than?(rectangle)如果正方形大于矩形,则为true;否则为false
以下是规格:
describe "Shape" do
describe "larger_than?" do
it "should tell if a shape is larger than another shape" do
class A < Shape
def area
5
end
end
class B < Shape
def area
10
end
end
a = A.new
b = B.new
expect( b.larger_than?(a) ).to eq(true)
expect( a.larger_than?(b) ).to eq(false)
end
end
This is my code:
class Shape
attr_accessor :color
def initialize(color = nil)
@color = color || 'Red'
end
def larger_than?
if Shape.new.area > self.class.area
true
else
false
end
end
end
class Rectangle < Shape
attr_accessor :width, :height
def initialize(width, height, color = nil)
@width, @height = width, height
super(color)
end
def area
width * height
end
end
class Square < Rectangle
def initialize(side, color = nil)
super(side, side, color)
end
end
class Circle < Shape
attr_accessor :radius
def initialize(radius, color = nil)
@radius = radius
super(color)
end
def area
Math::PI * (radius * radius)
end
end错误:
ArgumentError
wrong number of arguments (1 for 0)
exercise.rb:8:in `larger_than?'
exercise_spec.rb:18:in `block (3 levels) in <top (required)>'我真的很感谢大家对我的遗漏/错误之处的反馈。
发布于 2014-12-07 17:37:18
免责声明:我试着不给你解决方案,而是提示你自己去获取解决方案。
除了larger_than?方法之外,您的代码看起来很不错。再想想这个方法是如何调用的:
square.larger_than?(rectangle)它是在一个Shape对象上调用的,第一个参数是另一个Shape对象。
因此,该方法需要一个参数(另一个形状)。在该方法中,可以使用self访问当前形状,并使用另一个形状(使用参数)来比较这两个区域。
还有一件小事:你正在做这个:
if Shape.new.area > self.class.area
true
else
false
endif语句中的测试表达式已经返回了一个Boolean (第一种情况下为true,第二种情况下为false )。因此,您可以直接返回测试表达式的值,而不是编写if语句。
更新
larger_than?方法应如下所示:
def larger_than?(otherShape)
self.area > otherShape.area
endself是调用larger_than?方法的形状。要比较这两个形状,必须比较这两个形状的面积。
https://stackoverflow.com/questions/27341240
复制相似问题