diff --git a/README.md b/README.md index 816835f5b..01eef792e 100644 --- a/README.md +++ b/README.md @@ -2447,6 +2447,72 @@ condition](#safe-assignment-in-condition). end ``` +* + Prefer `alias` when aliasing methods in lexical class scope as the + resolution of `self` in this context is also lexical, and it communicates + clearly to the user that the indirection of your alias will not be altered + at runtime or by any subclass unless made explicit. +[[link](#alias-method-lexically)] + + ```Ruby + class Westerner + def first_name + @names.first + end + + alias given_name first_name + end + ``` + + Since `alias`, like `def`, is a keyword, prefer bareword arguments over + symbols or strings. In other words, do `alias foo bar`, not + `alias :foo :bar`. + + Also be aware of how Ruby handles aliases and inheritance: an alias + references the method that was resolved at the time the alias was defined; + it is not dispatched dynamically. + + ```Ruby + class Fugitive < Westerner + def first_name + 'Nobody' + end + end + ``` + + In this example, `Fugitive#given_name` would still call the original + `Westerner#first_name` method, not `Fugitive#first_name`. To override the + behavior of `Fugitive#given_name` as well, you'd have to redefine it in the + derived class. + + ```Ruby + class Fugitive < Westerner + def first_name + 'Nobody' + end + + alias given_name first_name + end + ``` + +* + Always use `alias_method` when aliasing methods of modules, classes, or + singleton classes at runtime, as the lexical scope of `alias` leads to + unpredictability in these cases. +[[link](#alias-method)] + + ```Ruby + module Mononymous + def self.included(other) + other.class_eval { alias_method :full_name, :given_name } + end + end + + class Sting < Westerner + include Mononymous + end + ``` + ## Exceptions * @@ -3393,10 +3459,6 @@ condition](#safe-assignment-in-condition). Foo.bar = 1 ``` -* - Avoid `alias` when `alias_method` will do. -[[link](#alias-method)] - * Use `OptionParser` for parsing complex command line options and `ruby -s` for trivial command line options.