Well... having a topic start with a question, which is followed by some code answering that very question, is indeed a bit special.
Yes. You can perfectly fine overwrite an alias, it is nothing special. Dekita, your problem stems from your conceptual model of overwriting and aliasing.
Let's say you have some example code (continuous example, all code pieces are assumed to be put in continuation of each-other)
Code:
# Small example classclass Foo attr_accessor :my_attribute def hello 'Hello' endend# We can call our methodfoo = Foo.newp foo.hello #=> Hello
foo.hello simply points to a method. We have on our foo object a method name
hello pointing to a method we created. It is perfectly possible to take the method an play around with it:
Code:
# Let's fetch ithello_method = foo.method(:hello)# Look, it can be called!p hello_method.call #=> Hello
Overwriting a method simply means to make the method name point to another method. That's it.
Code:
# Overwrite -> Create a new method and let :hello method point to itclass Foo def hello 'World' endend# Yup, an overwritten methodp foo.hello #=> World# We can still call the old methodp hello_method.call #=> Hello
Of course, we didn't have a reference to the method it will eventually be destroyed by the garbage cleaner. Since we have a reference, let's play around with it instead:
Code:
# But what about the old method?foo.my_attribute = hello_method# Yup, we can still use itp foo.my_attribute.call #=> Hello
Yup, a method is an object, so we can treat it as one.
Now that we understand a bit about methods and overwrites let us take a look at aliasing:
Code:
# Ok, let us try some aliasingclass Foo alias :world :helloend# Let us try calling themp foo.hello #=> Worldp foo.world #=> World# Yup, they are in fact pointing to the same elementp foo.method(:hello) == foo.method(:world) #=> truep hello_method == foo.method(:world) #=> false
Look at that, alias simply gives us another method name pointing to the same method object. Aliasing does not copy methods. True, when you give a method more than one name you can still access it if one of the names is overwritten.
To give some extra information we can do the same in a different way. Hopefully this helps your understanding:
Code:
# Let us put the old method back with a little hackclass Foo def create_method(method_symbol, method) self.class.send(:define_method, method_symbol, method) endendfoo.create_method(:hello, hello_method)# What happens when we call the method again?p foo.hello #=> Hellop foo.method(:hello) == foo.method(:world) #=> false# No need for any pesking aliasfoo.create_method(:hello_take_two, hello_method)p foo.hello_take_two #=> Hellop foo.method(:hello) == foo.method(:hello_take_two) #=> true
For more information on this subject I highly recommend
The Ruby Object Model by Dave Thomas