class - NoMethodError, undefined method in Ruby

I am new to Ruby and I'm working on an exercise about Classes and Inheritance.

The instructions are as follows:

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:

I am having problems creating the larger_than? method. I don't know how to get the area from the other shapes and compare it to the receiving object's area.

Here's my code:

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

I don't understand why I'm facing this error:

NoMethodError
undefined method `larger_than?' for #<B:0x007fdf3047d5a8 @color="Red">

1 Answer

  1. Keith- Reply

    2019-11-13

    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).

    I'm assuming line 4 is this

    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

    So two problems

    1. Why is area in Shape class a Class method? self.area - means it's executed as Shape.area not Shape.new.area - which I think is what you wanted.
    2. You can't compare nil (which is what Shape.area -returns. Empty methods return nil, since there is nothing else for them to do) and a number. You could coerse nil into an integer like so nil.to_i => 0 and then do a comparison, but I don't think that's what you intended.

    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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>