Home > Software design >  Inheritance of constructors in Ruby
Inheritance of constructors in Ruby

Time:09-25

Lets say I create a new class which inherits from Symbol. Symbols are unique and it is very clear that the Symbol class has no Constructor. But which mechanism prevents the creation of a constructor in the child class? Is there some flag which makes all children unique?

class Syb < Symbol
   def initialize
   end
end
p Syb.respond_to? :new
false

CodePudding user response:

First of all I also believe that is not a good idea to extend ruby core classes, references

In this case in particular

"For efficiency, many core class methods are coded in C instead of Ruby. And in some cases, such as this Array addition operator, they are implemented in such a way that the class of the return value is hardcoded."

If you take a look of the initialize method in the ruby Symbol class (it really has):

[36] pry(main)> require 'pry-doc'
=> true
[72] pry(main)> cd Symbol
[73] pry(Symbol):1> $ initialize

From: object.c (C Method):
Owner: BasicObject
Visibility: private
Signature: initialize()
Number of lines: 5

static VALUE
rb_obj_dummy0(VALUE _)
{
    return rb_obj_dummy();
}

So we can see that this method allready exists and it is implemented in c, but there is a limitation about overiding ruby core classes methods, explained in this answer

And I also believe that is really important to investigate ruby with, pry pry-doc and pry-gem

CodePudding user response:

As Sergio stated, my mistake was the mix up of constructor and initializer. Actually it is possible to write a new constructor for the Symbol class.

irb(main):001:1* class Symbol
irb(main):002:2*   def Symbol.new x
irb(main):003:2*     x.to_sym
irb(main):004:1*   end
irb(main):005:0> end
=> :new
irb(main):008:0> a = Symbol.new "xyz"
=> :xyz
irb(main):009:0> a
=> :xyz

Yes I realize that here the symbol is actually created by the .to_sym method. So new is not really a constructor but more like a wrapper for the real constructor.

  • Related