TypeError: superclass mismatch for class Word in Ruby

前端 未结 4 1324
生来不讨喜
生来不讨喜 2020-12-05 17:37

I am creating a Word class and I am getting an error:

TypeError: superclass mismatch for class Word

Here is the

相关标签:
4条回答
  • 2020-12-05 18:11

    A thumb rule for irb (either way irb or rails console)

    If you are creating the same class twice with inheritance (superclass), exit the irb instance and create it again. Why this? Because otherwise class conflicts will happen.

    In your case, you are using Windows (found from the question), so just type exit on DOS prompt and again type irb or rails console and create your Word class and it should work. Please let me know if it doesn't work for you.

    0 讨论(0)
  • 2020-12-05 18:16

    The reason it gives you a superclass mismatch error is because you have already defined the Word class as inheriting from Object

    class Word
    ...
    end
    

    In Ruby (like in most dynamic languages) you can monkey-patch classes by reopening the definition and modifying the class. However, in your instance, when you are reopening the class you are also attempting to redefine the class as inheriting from the super class String.

    class Word < String
    ...
    end
    

    Once a class and it's inheritance structure have been defined, you cannot define it again.

    As a few people have said, exiting and restarting irb will allow you to start from scratch in defining the Word class.

    0 讨论(0)
  • 2020-12-05 18:16

    An easy way to bypass this issue is to encapsulate both classes between different modules:

    > module M
    >     class Word
    >         def palindrome?(string)
    >             string == string.reverse
    >         end
    >     end
    > end
    => nil
    > w = M::Word.new
    => #<Word:0x4a8d970>
    > w.palindrome?("foobar")
    => false
    > w.palindrome?("level")
    => true
    > module N
    >     class Word < String
    >         def palindrome?
    >             self == self.reverse
    >         end
    >     end
    > end
    > N::Word.new("kayak").palindrome?
    => true
    
    0 讨论(0)
  • 2020-12-05 18:26

    link664 has clearly explained the problem.

    However, there's an easier fix without quitting irb (and losing all your other work). You can delete an existing class definition this way.

    irb(main):051:0> Object.send(:remove_const, :Word)
    

    and you can verify with:

    irb(main):052:0> Word.public_instance_methods
    

    which should return:

    NameError: uninitialized constant Word
    from (irb):52
    
    0 讨论(0)
提交回复
热议问题