在Ruby中,多態性允許對象對不同的方法調用作出響應。為了避免命名沖突,你可以采取以下幾種策略:
module MyModule
def my_method
puts "This is my method"
end
end
class MyClass
include MyModule
def my_method
puts "This is my class method"
end
end
obj = MyClass.new
obj.my_method # 輸出 "This is my class method"
class MyNamespace::MyClass
def my_method
puts "This is my method"
end
end
obj = MyNamespace::MyClass.new
obj.my_method # 輸出 "This is my method"
alias_method
:如果你需要在子類中重寫父類的方法,但又不想改變方法名,可以使用alias_method
來為父類的方法創建一個新的別名。class MyBaseClass
def my_method
puts "This is my base class method"
end
end
class MyDerivedClass < MyBaseClass
def my_method
puts "This is my derived class method"
end
alias_method :old_my_method, :my_method
end
obj = MyDerivedClass.new
obj.my_method # 輸出 "This is my derived class method"
obj.old_my_method # 輸出 "This is my base class method"
super
關鍵字:在子類中重寫父類的方法時,可以使用super
關鍵字來調用父類的實現,從而避免死循環。class MyBaseClass
def my_method
puts "This is my base class method"
end
end
class MyDerivedClass < MyBaseClass
def my_method
puts "This is my derived class method"
super
end
end
obj = MyDerivedClass.new
obj.my_method # 輸出 "This is my derived class method" 和 "This is my base class method"
遵循這些策略,你可以在Ruby中有效地利用多態性,同時避免命名沖突。