First, let's look at the alias. In Ruby, we can create an alias for the method or global variable. What's interesting is that after the method alias is defined, even if the corresponding method isCodeAfter a new definition (that is, an internal implementation is modified), the alias can still be called to the method before modification, but the global variable cannot.
Def meth puts "this is meth" endalias: orgin_meth: methmeth # => This is methorgin_meth # => This is methdef meth puts "A new meth" endmeth # => A new methorgin_meth # => This is meth (note that the old method is retained here. features) $ A = 1 alias $ B $ A # set global variable A and alias B $ B = 2 p $, $ B # => (note that the method alias is different)
Let's talk about method cancellation:
UNDEF or undef_method can be used to cancel the definition of Class methods (or delete them completely). This is not easy to understand, but note the following: if a class inherits from the parent class and defines a method with the same name as the parent class, after UNDEF is used to cancel the method, cancels a method with the same name as the joint parent class (in fact, it is also normal: in the Dynamic Language World, the subclass redefines the cognominal method inherited by the parent class, which is equivalent to overwriting the method, therefore, when a subclass instance is called, you can only call the method of the same name as the subclass itself. Once the method is canceled, the method [whether it is the parent class or the subclass] will not be concerned with the subclass)
Class base def meth puts "base. meth "endendclass subclass1 <base def Meth # is equivalent to rewriting the meth method puts of the parent class" subclass1.meth "End def meth2 puts" subclass1.meth2 "End ends1 = subclass1.news1. meth # => subclass1.meths1. meth2 # => subclass1.meth2class subclass1 UNDEF: meth2 # undef_method (: meth2) # This sentence is equivalent to the above UNDEF: Meth # Note: After the definition of meth is canceled, even the meth inherited by the parent class cannot call end # s1.meth # An error will be reported.
What if we only want to cancel the method in the subclass and keep the method of the same name inherited by the parent class? The answer is: remove_method. Change the last part of the previous code:
Class subclass1 UNDEF: meth2 # undef_method (: meth2) # This sentence is equivalent to the remove_method (: Meth) above # only remove the meth method of the subclass ends1.meth # => base. Meth
We can see that the meth method of the parent class is used when s1.meth is called.