liveBook · Manning

Alias

As explained in The Well-Grounded Rubyist, Fourth Edition

alias is a Ruby language construct that gives a method or other name an additional name without changing its behavior or method lookup.

Suppose you want to log every call to String#reverse while leaving its result alone. Give the existing method another name, redefine reverse to print a message, then call the saved name. Ruby’s alias keyword creates that second name; calling it does not change the method’s behavior or method lookup. section 13.2.3 section 13.2.1

class String
  alias __old_reverse__ reverse
  def reverse
    $stderr.puts "Reversing a string!"
    __old_reverse__
  end
end
puts "David".reverse

The alias is created before reverse is redefined. The new reverse prints to STDERR, then calls __old_reverse__; that call supplies the return value. section 13.2.3

Ruby also provides Module#alias_method. Write `alias __old_reverse__ reverse` with bare names and no comma, or `alias_method :__old_reverse__, :reverse` with symbols. Unlike alias, alias_method is a method; it also accepts strings as arguments. section 13.2.3

Keeping the original available does not make every override safe. An override of Regexp#match can call an alias of the original and return an empty array when the original returns nil. Indexing a failed match then works, but an `if` test that previously detected failure now succeeds: an empty array is true, while nil is false. Preserve the original return behavior when callers rely on it. section 13.2.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines alias as a method-name synonym, contrasts its syntax with alias_method, and explains override behavior without changing method lookup.
Examples
Uses String#reverse for logging and Regexp#match for a failed-match override that changes conditional behavior.
What it assumes
Assumes familiarity with Ruby class and method definitions, while defining alias and distinguishing it from alias_method.
What you can do after
Practice/perform it by aliasing a method before overriding it, then calling the original while checking whether the return contract remains intact.
How it connects
Connects alias to method overriding, method lookup, Module#alias_method, return values, and truthiness.

Also explained in

Compare how 6 books explain alias →

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.