4

I've just made this experiment:

class A < Hash
  def foo
    'foo'
  end
end

class A < Hash
  def bar 
    'bar'
  end
end

So far I get the result I expected, the second declaration extends the first one. However I was surprised of this:

class A
  def call
    puts foo
    puts bar
  end
end

The code above works, but only if I declare it later. Otherwise I get:

TypeError: superclass mismatch for class A

Can I assume that in Ruby, it is safe skipping the superclass specification without side effects after making sure that the "original-first" declaration was parsed?

2
  • Yes, that is correct. Commented Jan 31, 2014 at 15:16
  • In you last attempt, it tries to make an Object class, as its superclass.. So the error you got.. and it is expected.. Commented Jan 31, 2014 at 15:18

2 Answers 2

3

You are able to declare inheritance only on the first occurince of the class definition, so below variants will work:

  1. When you've defined the same class inheritance:

    class A < Hash
    end
    
    class A < Hash
    end
    
  2. When you've used default inheritance in the second case, that is treated as undefined inheritance:

    class A < Hash
    end
    
    class A
    end
    
  3. When you've used default inheritance in both cases, the default inheritance is of Object class:

    class A
    end
    
    class A
    end
    

And below will not:

  1. When you've used default inheritance in the first case, and next you tried to redefine it explicitly:

    class A
    end
    
    class A < Hash
    end
    
    TypeError: superclass mismatch for class A
    
  2. When you've used specified inheritance (in example String) in the first case, and next you tried to redefine it explicitly (in example with Hash):

    class A < String
    end
    
    class A < Hash
    end
    
    TypeError: superclass mismatch for class A
    
Sign up to request clarification or add additional context in comments.

Comments

1

@Малъ Скрылевъ explained this case a better way, so I wouldn't attempt that. But I would show you another way to do this.

One way to avoid the error is in your situation :

Instead of writing

class A
  def call
    puts foo
    puts bar
  end
end

Write it as below using Module#class_eval:

Evaluates the string or block in the context of mod, except that when a block is given, constant/class variable lookup is not affected. This can be used to add methods to a class. module_eval returns the result of evaluating its argument.

A.class_eval do
  def _call
    puts foo
    puts bar
  end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.