Reputation: 26973
I have the following Ruby code that features an alias
in a child class of a method that's defined in the superclass, and overridden in the child class:
class Parent
def hello
print "Hello, I'm Parent!"
end
end
class Child < Parent
alias greet hello
def hello
print "Hi, I'm Child!"
end
end
When I call the greet
alias on an instance of Child
, it calls the Parent
implementation of hello
, not its own class's implementation. For example, with the above code loaded in irb:
2.3.3 :001 > child = Child.new
=> #<Child:0x007fb1118a8f58>
2.3.3 :002 > child.hello
Hi, I'm Child! => nil
2.3.3 :003 > child.greet
Hello, I'm Parent! => nil
2.3.3 :004 >
How can I get the alias to point to the local implementation of the method instead of the parent class implementation?
Upvotes: 1
Views: 71
Reputation: 26973
The alias
needs to be located after the method to be aliased, not before.
This revised code for the Child class will have greet
aliased to the local implementation of hello
, as intended:
class Child < Parent
def hello
print "Hi, I'm Child!"
end
alias greet hello
end
Upvotes: 2