0
votes

Is it possible with Ruby to instantiate a class and store the instance within the same class as constant?

class MyClass

   DEFAULT = MyClass.new("haha")

   def initialize(arg)
      puts(arg)
   end
end

# use it
instance1 = MyClass::DEFAULT
instance2 = MyClass.new("hohoho")

I tried this, but I get some strange results: 'initialize': wrong number of arguments (given 1, expected 0) (ArgumentError) at the line of the DEFAULT declaration.

2

2 Answers

4
votes

but I get some strange results: 'initialize': wrong number of arguments (given 1, expected 0) (ArgumentError)

Your one-argument initialize method is not yet defined at this point. But there is a default one, which doesn't take any arguments. Hence the error.

Move that constant after the method (and also all other methods your initializer might call).

1
votes

You say you wish to, "instantiate a class and store the instance within the same class as constant". I interpreted that as, "instantiate a class and store the same instance within the class as a constant". That also seems to be consistent with the question's title.

You can do that as follows.

class MyClass
  def initialize(arg)
    puts(arg)
    self.class.const_set(:DEFAULT, self)
  end
end

MyClass.new('hi')
hi
  #=> #<MyClass:0x00005c3edb328a40> 

MyClass.constants
  #=> [:DEFAULT]

MyClass::DEFAULT
  #=> #<MyClass:0x00005c3edb328a40>