0
0
RubyConceptBeginner · 3 min read

Alias Method in Ruby: What It Is and How to Use It

In Ruby, the alias keyword creates a new name for an existing method, allowing you to call the same method using different names. It helps keep code flexible by giving methods alternative names without duplicating code.
⚙️

How It Works

The alias keyword in Ruby works like giving a nickname to a method. Imagine you have a friend named "Jonathan" but you also call him "Jon". Both names point to the same person. Similarly, alias lets you use two names for one method.

When you use alias, Ruby creates a new method name that points to the original method's code. This means you can call the method by either name, and it will do the same thing. It does not copy the method but just creates another label for it.

This is useful when you want to keep old method names for compatibility or provide clearer method names without changing the original method.

💻

Example

This example shows how to use alias to create a new name for an existing method.

ruby
class Greeter
  def hello
    "Hello!"
  end

  alias greet hello
end

g = Greeter.new
puts g.hello
puts g.greet
Output
Hello! Hello!
🎯

When to Use

Use alias when you want to keep an old method name while introducing a new one, such as during code refactoring. It helps maintain backward compatibility so existing code using the old name still works.

It is also helpful when you want to provide a more descriptive or shorter method name without rewriting the method's code. For example, you might alias a long method name to a shorter one for convenience.

Another use case is when you want to override a method but still keep the original method accessible under a different name.

Key Points

  • Alias creates a new name for an existing method without copying it.
  • Both names call the same method code.
  • Useful for backward compatibility and clearer method names.
  • Helps when overriding methods but keeping original access.

Key Takeaways

The alias method creates a new name for an existing method in Ruby.
Both the original and alias names call the same method code.
Use alias to keep old method names during refactoring or to add clearer names.
Alias helps maintain backward compatibility without duplicating code.
It is useful when overriding methods but needing access to the original.