๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

Ruby Const Missing

A program can ask a module or class for a constant that was never defined. const_missing catches that ask and supplies the answer.

A module answers with a default

Settings defines self.const_missing to print the asked name and return a default string. Asking for TIMEOUT runs it.

module Settings
  def self.const_missing(name)
    puts "Missing constant #{name}"
    "default"
  end
end
puts Settings::TIMEOUT

A class builds from the name

Label builds each answer from the asked name. URGENT and QUIET each produce their own label text.

class Label
  def self.const_missing(name)
    "Label for #{name.to_s.downcase}"
  end
end
puts Label::URGENT
puts Label::QUIET

A defined constant skips it

LIMIT is defined inside Config, so asking for it prints 10 with no extra line. Asking for OTHER runs const_missing and prints its line first.

module Config
  LIMIT = 10
  def self.const_missing(name)
    puts "const_missing called for #{name}"
    0
  end
end
puts Config::LIMIT
puts Config::OTHER

Example

module Dictionary
  GREETING = "hello"
  def self.const_missing(name)
    "No entry for #{name.to_s.downcase}"
  end
end
puts Dictionary::GREETING
puts Dictionary::FAREWELL

Key points

  • const_missing runs when code asks for an undefined constant.
  • It is defined on the module or class itself with self.const_missing.
  • The asked name arrives as a symbol argument.
  • The value const_missing returns becomes the value of the constant ask.
  • A class can build its answer from the asked name.
  • A defined constant answers directly and never triggers const_missing.

In this example, Dictionary defines GREETING, so that ask answers hello directly. FAREWELL was never defined, so const_missing builds a message from the asked name instead.

Note

const_missing runs once for each ask of an undefined constant.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

When does const_missing run?