liveBook · Manning

Core class

As explained in The Well-Grounded Rubyist, Fourth Edition

A core class is a fundamental class provided by the Ruby language implementation and available to programs by default.

A core class is a fundamental Ruby class, such as Regexp or String, whose behavior is available throughout a running program. Changing a core class changes the rules for every code path that uses it, including Ruby internals and loaded libraries. section 13.2.1

Ruby lets you customize core classes, but global overrides are the least safe approach. An alias can preserve the original method for a pass-through override, yet the replacement still affects every caller. Additive overrides, extend, and refinements provide other ways to change behavior with greater control. section 13.2.1 section 13.4

Why changing return behavior is risky

Regexp#match returns a MatchData object when matching succeeds and nil when it fails. Replacing nil with an empty array may prevent one indexing error, but it changes the method's behavior for all code using Regexp. Similarly, String#gsub! returns nil when no substitution occurs, so chaining reverse! directly after a failed substitution raises NoMethodError. section 13.2.1 section 13.2.1

class Regexp
  alias __old_match__ match        1
  def match(string)
    __old_match__(string) || []
  end
end

Inspect a pass-through override that aliases Regexp#match, delegates to the original implementation, and substitutes an empty array for nil. section 13.2.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains global mutation, alias-based delegation, return-value edge cases, and safer alternatives without detailing their implementations.
Examples
Uses Regexp#match overrides, String#gsub! return values, failed chaining, and conditional or iterative substitutions.
What it assumes
Assumes familiarity with Ruby methods, classes, nil, aliases, and conditional method results.
What you can do after
Evaluate core-class customizations and diagnose failures caused by changed return values or globally altered methods.
How it connects
Connects core classes with method aliasing, method lookup, singleton classes, modules, refinements, and object behavior.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.