I'm getting a mismatch error and I've looked up why it would appear and I'm confused because what I'm doing doesn't match the error cause. Plus I've followed the instructions from a guide that I'm using.
The code on irb...

>> class Cat
>> attr_accessor :name, :age, :gender
>> end
=> nil
>> class Pets
>> attr_accessor :name, :age, :gender
>> end
=> nil
>> class Cat < Pets
>> end
TypeError: superclass mismatch for class Cat
from (irb):24

any thoughts? thanks.

Recommended Answers

All 3 Replies

Perhaps you meant something like

class Pet
    attr_accessor :name, :age, :gender
end 

class Cat < Pet
end

where Cat is a derivative of Pet ?

What you have doesnt make very much sense. you create two distinct classes and then try to create another class (of the same name) and have a relationship between them. You need to associate the super/sub class relationship when you create the class the first time otherwise you get this ambiguity you are seeing.

I'll test it out and see if I get the error again. It's strange because I explicitly followed the tutorial's instructions.

So if I understand this correctly... first it creates the superclass Pet and then creates the class Cat which automatically has the attributes defined in the superclass Pet?

If I want to add attributes to the subclass Cat do I simply re-define it using attr_accessor ?

The sub class inherits all attribute from the parent. For instance:

class Pet 
   attr_accessor :name
end

class Cat < Pet
end

c = Cat.new
c.name = "Freddy"    # <= Okay
c.weight = 32        # <= Error, no method defined
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.