Question

If I have a class B that inherits from class A, can I instantiate class B through a class method defined in class A?

class A
  def self.instantiate params
    # ???
  end
end

class B < A
end

b = B.instantiate 123
b.class   # => B

Obviously, I don't want to call B.new from A. Any class that inherits from A should benefit from this.

class C < A; end
c = C.instantiate 123
c.class   # => C

class D < A; end
d = D.instantiate 123
d.class   # => D
Was it helpful?

Solution

Simply call self.new (self references the class itself in the class method):

class A
  def self.instantiate params
    self.new
    # OR simply `new`
  end
end

class B < A; end
b = B.instantiate 123
b.class
# => B

class C < A; end
c = C.instantiate 123
c.class
# => C

class D < A; end
d = D.instantiate 123
d.class
# => D

UPDATE

As Cary Swoveland commented, you can omit self.:

  def self.instantiate params
    new
  end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top