Ruby class class without inheritance

I just did this experiment:

class A < Hash
  def foo
    'foo'
  end
end

class A < Hash
  def bar 
    'bar'
  end
end

As long as I get the expected result, the second declaration extends the first. However, I was surprised by this:

class A
  def call
    puts foo
    puts bar
  end
end

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

TypeError: superclass mismatch for class A

Can I assume that it is safe in Ruby to skip a superclass specification without side effects after making sure that the original-first declaration has been parsed?

+4
source share
2 answers

You can declare inheritance only at the first appearance after the class definition, so the options below will work:

  • If you defined the same class inheritance:

    class A < Hash
    end
    
    class A < Hash
    end
    
  • , undefined inheritance:

    class A < Hash
    end
    
    class A
    end
    
  • , Object class:

    class A
    end
    
    class A
    end
    

:

  • , :

    class A
    end
    
    class A < Hash
    end
    
    TypeError: superclass mismatch for class A
    
  • ( String) , ( Hash):

    class A < String
    end
    
    class A < Hash
    end
    
    TypeError: superclass mismatch for class A
    
+3

@ , . .

:

class A
  def call
    puts foo
    puts bar
  end
end

, , Module#class_eval:

, , , , / . . module_eval .

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

Source: https://habr.com/ru/post/1524723/


All Articles