0

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
garbagecollector
  • 3,731
  • 5
  • 32
  • 44

1 Answers1

1

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
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    You don't need `self.` in `self.new`; `new` is sufficient. – Cary Swoveland May 05 '14 at 05:09
  • @CarySwoveland, Thank you for comment. I updated the answer according to your comment. – falsetru May 05 '14 at 05:34
  • 1
    Of course, all that you have done here is simply hand-written an alias for `new`. So, you might just as well do `alias_method :instantiate, :new`. But then you might just as well call `new` … Honestly, I don't understand the requirements of the OP. – Jörg W Mittag May 05 '14 at 09:50