Search code examples
rubyclassinstantiation

Is this singleton example legal in Ruby?


Adapted the example from this link. Not sure what's wrong with invoking Logger.create.id, or shall I invoke l = Logger.new first?

class Logger
  private_class_method :new
  @@logger = nil

  def Logger.create
    @@logger = new unless @@logger
    @@logger
  end
end

Logger.create.id

Solution

  • Your code is fine, except for the last line. Perhaps you meant:

    p Logger.create.object_id