[英]NoMethodError, undefined method in Ruby
I am new to Ruby and I'm working on an exercise about Classes and Inheritance . 我是Ruby的新手,正在从事有关类和继承的练习。
We should be able to call a larger_than? 我们应该能够调用一个更大的比? method on each shape.
每个形状的方法。 This method should evaluate two shapes and return true or false depending on one shape's area being larger than the other.
此方法应评估两个形状,并根据一个形状的面积大于另一个形状的面积返回真或假。 In other words, the larger_than?
换句话说,“大于”? method should return true if the receiving object is larger than the argument object:
如果接收对象大于参数对象,则方法应返回true:
I am having problems creating the larger_than? 我在创建large_than时遇到问题吗? method.
方法。 I don't know how to get the area from the other shapes and compare it to the receiving object's area.
我不知道如何从其他形状中获取面积并将其与接收对象的面积进行比较。
class Shape
attr_accessor :color, :area
def initialize(color = nil)
@color = color || 'Red'
end
def larger_than?(object_area)
if self.class.area > object_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) # this calls Shape#initialize
end
def area
width * height
end
end
class Square < Rectangle
def initialize(side, color = nil)
super(side, side, color) # calls `Rectangle#initialize`
end
end
class Circle < Shape
attr_accessor :radius
def initialize(radius, color = nil)
@radius = radius
super(color) # this calls Shape#initialize
end
def area
Math::PI * (radius*radius)
end
end
NoMethodError
undefined method `larger_than?' for #<B:0x007fdf3047d5a8 @color="Red">
It would be helpful if you provided actuall code that calls this comparison, but based on this code you are trying to compare a value of Fixnum class ( essentially an integer) to a NilClass (essentially nothing). 如果您提供了调用此比较的实际代码,这将很有帮助,但是基于此代码,您试图将Fixnum类的值(本质上是一个整数)与NilClass(基本上什么都没有)进行比较。
I'm assuming line 4 is this 我假设第4行是这个
if shape.area > self.class.area
I'm assuming when you call this line shape.area contains some kind of number of class Fixnum that gets calculated somewhere as Instance method , while you are comparing it to a Class method 我假设当您调用此线形时.area包含某种数量的Fixnum类,在将其与Class方法进行比较时会以Instance方法的形式进行计算
So two problems 所以两个问题
If you could provide a piece of code that actually calls these classes or explain what you are trying to do - I would be able to help you further. 如果您可以提供一段实际调用这些类的代码或解释您要执行的操作-我将能够为您提供进一步的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.