Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 66 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2447,6 +2447,72 @@ condition](#safe-assignment-in-condition).
end
```

* <a name="alias-method-lexically"></a>
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.
<sup>[[link](#alias-method-lexically)]</sup>

```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
```

* <a name="alias-method"></a>
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.
<sup>[[link](#alias-method)]</sup>

```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

* <a name="fail-method"></a>
Expand Down Expand Up @@ -3393,10 +3459,6 @@ condition](#safe-assignment-in-condition).
Foo.bar = 1
```

* <a name="alias-method"></a>
Avoid `alias` when `alias_method` will do.
<sup>[[link](#alias-method)]</sup>

* <a name="optionparser"></a>
Use `OptionParser` for parsing complex command line options and `ruby -s`
for trivial command line options.
Expand Down