鑑於以下代碼:Ruby如何區分Method和Method =(參數)(同名getter/setter方法)?
class Animal
def noise=(noise)
@noise = noise
end
def noise
@noise
end
end
animal1 = Animal.new
animal1.noise = "Moo!"
puts animal1.noise
animal2 = Animal.new
animal2.noise = "Quack!"
puts animal2.noise
如何紅寶石噪聲和噪聲區分=(參數)?通常,在Ruby中寫出兩種方法時,最新的方法會勝出,但只是想知道如何以這種方式寫入兩個同名的方法,而不會覆蓋另一個方法。
在一種情況下該方法的名稱包括等號:':噪聲='。 Ruby允許你將它寫成'noise =(other)'或'noise = other'。後者有時被稱爲「語法糖」。 –
你從哪裏知道他們有相同的名字?它們顯然是不同的:「def」之後和參數之前的字符串是名稱。 –
我從animal1.noise =「Moo!」這一事實中得到了答案。並放入animal1.noise有一個相同的字符串(animal1.noise)。在等號之後,我假設所有的東西都是方法的一部分,而不是方法的名稱。 – the12