Ruby Logo

Method Aliasing & Method Missing

Learn method aliasing with alias_method, method redefinition, and dynamic method handling with method_missing.

Home Ruby Method Aliasing & Method Missing

Method Aliasing & Method Missing

Ruby's method aliasing system allows you to create alternative names for methods, while method_missing provides a powerful way to handle undefined method calls dynamically. These features enable flexible and expressive Ruby programming.

Method Aliasing

Method Aliasing: Create alternative names for existing methods using alias_method or alias. Useful for backward compatibility, API design, and method enhancement.

Basic Method Aliasing

# Basic method aliasing
class
String
alias_method :old_reverse, :reverse
def reverse
puts "Reversing string..."
old_reverse
end
end

text = "hello"
puts text.reverse
# "Reversing string..." then "olleh"
puts text.old_reverse
# "olleh" (original method)

Alias vs Alias Method

# Using alias (syntax sugar)
class
Calculator
def add(a, b)
a + b
end
alias plus add # Creates alias 'plus' for 'add'
end

calc = Calculator.new
puts calc.add(5, 3)
# 8
puts calc.plus(5, 3)
# 8

# Using alias_method (more flexible)
class
Calculator
alias_method :subtract, :minus # Can use symbols or strings
alias_method "multiply", "times"
end

Method Missing

Method Missing: Ruby calls method_missing when a method is not found. Override it to create dynamic method handling, DSLs, and flexible APIs.

Basic Method Missing

# Basic method_missing implementation
class
DynamicCalculator
def initialize
@operations = {}
end
def method_missing(method_name, *args, &block)
if method_name.to_s.start_with?("calculate_")
operation = method_name.to_s.gsub("calculate_", "")
puts "Performing \#{operation} with \#{args.join(', ')}"
return 42 # Placeholder result
end
super # Call parent method_missing
end
end

calc = DynamicCalculator.new
puts calc.calculate_add(5, 3)
# "Performing add with 5, 3" then 42
puts calc.calculate_multiply(4, 7)
# "Performing multiply with 4, 7" then 42
# calc.unknown_method
# NoMethodError

Advanced Method Missing

# Dynamic attribute accessor
class
DynamicHash
def initialize
@data = {}
end
def method_missing(method_name, *args)
method_str = method_name.to_s
if method_str.end_with?("=")
# Setter method (name=)
key = method_str.chomp("=").to_sym
@data[key] = args.first
else
# Getter method
@data[method_name]
end
end
end

hash = DynamicHash.new
hash.name = "Alice"
hash.age = 25
puts
hash.name
# "Alice"
puts
hash.age
# 25

Respond To Method

Respond To Method: Override respond_to? to make your dynamic methods work properly with introspection and duck typing.

Respond To Method Example

# Complete dynamic method implementation
class
SmartCalculator
def method_missing(method_name, *args)
if method_name.to_s.start_with?("calculate_")
operation = method_name.to_s.gsub("calculate_", "")
case operation
when "add" then args.reduce(:+)
when "multiply" then args.reduce(:*)
else super
end
else
super
end
end
def respond_to_missing?(method_name, include_private = false)
method_name.to_s.start_with?("calculate_") || super
end
end

calc = SmartCalculator.new
puts calc.respond_to?(:calculate_add)
# true
puts calc.respond_to?(:calculate_multiply)
# true
puts calc.respond_to?(:unknown_method)
# false

puts calc.calculate_add(1, 2, 3)
# 6
puts calc.calculate_multiply(2, 3, 4)
# 24

Interactive Practice: Method Aliasing & Method Missing

Practice Time: Try these method aliasing and method_missing examples. Understanding these patterns will make you a more effective Ruby programmer.

Interactive Code Runner

Ruby Code Editor
Output will appear here when you run the code...

Best Practices & Common Patterns

✅ Best Practices

  • Always override respond_to_missing? with method_missing
  • Use alias_method for dynamic aliasing
  • Call super in method_missing for unknown methods
  • Document dynamic method patterns clearly
  • Use method_missing sparingly - prefer explicit methods
  • Consider performance implications of dynamic methods

❌ Common Pitfalls

  • Forgetting to override respond_to_missing?
  • Not calling super in method_missing
  • Overusing method_missing for simple cases
  • Creating infinite loops in method_missing
  • Not handling edge cases in dynamic methods
  • Making methods too magical and hard to debug

Method Aliasing & Method Missing Mastery Summary

You've Mastered Method Aliasing & Method Missing!

Method Aliasing

Create alternative names for existing methods

Method Missing

Handle undefined method calls dynamically

Respond To

Make dynamic methods work with introspection

Method aliasing and method_missing are powerful Ruby features that enable dynamic programming patterns. Use them judiciously to create flexible, expressive APIs while maintaining code clarity and performance.

Quick Navigation

Related Topics

Video Tutorial

Watch and learn method aliasing & method missing

Pro Tip: After reading through the content above, watch this video to reinforce your understanding and see the concepts in action!