Missing Methods and Missing Constants

The method_missing method is a key part of Ruby’s method lookup algorithm (see Method Lookup) and provides a powerful way to catch and handle arbitrary invocations on an object. The const_missing method of Module performs a similar function for the constant lookup algorithm and allows us to compute or lazily initialize constants on the fly. The examples that follow demonstrate both of these methods.

Unicode Codepoint Constants with const_missing

Example 8-3 defines a Unicode module that appears to define a constant (a UTF-8 encoded string) for every Unicode codepoint from U+0000 to U+10FFFF. The only practical way to support this many constants is to use the const_missing method. The code makes the assumption that if a constant is referenced once, it is likely to be used again, so the const_missing method calls Module.const_set to define a real constant to refer to each value it computes.

Example 8-3. Unicode codepoint constants with const_missing

# This module provides constants that define the UTF-8 strings for # all Unicode codepoints. It uses const_missing to define them lazily. # Examples: # copyright = Unicode::U00A9 # euro = Unicode::U20AC # infinity = Unicode::U221E module Unicode # This method allows us to define Unicode codepoint constants lazily. def self.const_missing(name) # Undefined constant passed as a symbol # Check that the constant name is of the right form. # Capital U followed by a hex number between 0000 and 10FFFF. if name.to_s ...

Get The Ruby Programming Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.