Noting highlights from the book Metaprogramming Ruby (2nd Edition).

Chapter 2. Monday: The Object Model

“For class, the core job is to move you in the context of the class, where you can define methods.”

  • Open Class Method: can always reopen an existing class and modify them on the fly
String.instance_methods.grep /^z/
=> []

class String
  def zang!
    upcase!
  end
end

String.instance_methods.grep /^z/
=> [:zang!]

'zang'.zang!
=> "ZANG"
  • Monkeypatch: Abusing Open Class method in a harmful way, e.g., overwriting existing methods of the same name and cause a previously reliable and stable method to break
  • The superclass of a class is Module - a class is simply a Module with 3 additional instance methods: new, allocate, superclass!
  • Namespace: A module that exists only to be a container of constants
  • Constants are scoped and can be accessed using paths via double colon
  • Leading double colon is shortcut to absolute path to a constant
  • Can call Module.nesting to get the current path
  • Loading & requiring: load is used for execution, has the side effect of polluting a program with the loaded file’s constants. Can pass true as a second argument to the load call to keep the file’s constants contained. This is accomplished by wrapping the file in a newly created anonymous namespace. require is used to loading libraries, and keeps the constants in the program so that we can use them!