alias | alias_method | |
|---|---|---|
| Loại | Keyword (cú pháp ngôn ngữ) | Method của Module |
| Cú pháp | alias new_name old_name (không dấu phẩy, chỉ symbol/bare word) | alias_method :new_name, :old_name (symbol/string, dấu phẩy) |
| Tên động | Không hỗ trợ | Có — nhận biến/expression |
| Kế thừa | Alias được resolve tại thời điểm định nghĩa (bind tĩnh) | Alias được resolve lúc gọi — override ở subclass hoạt động |
ruby
class Parent
def greet = "hello from Parent"
alias_method :hi, :greet
end
class Child < Parent
def greet = "hello from Child"
end
Child.new.hi # => "hello from Child" (alias_method — dynamic)
# Nếu dùng alias trong Parent:
# Child.new.hi # => "hello from Parent" (alias — static)Dùng alias_method trong module/metaprogramming.
Dùng alias khi cần cú pháp đơn giản trong class body.