patternrubyCritical
Should I use alias or alias_method?
Viewed 0 times
shouldalias_methodusealias
Problem
I found a blog post on
Usage of alias
Usage of alias_method
Blog post link here
alias vs. alias_method. As shown in the example given in that blog post, I simply want to alias a method to another within the same class. Which should I use? I always see alias used, but someone told me alias_method is better.Usage of alias
class User
def full_name
puts "Johnnie Walker"
end
alias name full_name
end
User.new.name #=>Johnnie WalkerUsage of alias_method
class User
def full_name
puts "Johnnie Walker"
end
alias_method :name, :full_name
end
User.new.name #=>Johnnie WalkerBlog post link here
Solution
alias_method can be redefined if need be. (it's defined in the Module class.)alias's behavior changes depending on its scope and can be quite unpredictable at times.Verdict: Use
alias_method - it gives you a ton more flexibility.Usage:
def foo
"foo"
end
alias_method :baz, :fooCode Snippets
def foo
"foo"
end
alias_method :baz, :fooContext
Stack Overflow Q#4763121, score: 392
Revisions (0)
No revisions yet.