Ruby重載知識(shí)講解
作者:佚名
Ruby重載在實(shí)際編程中是非常常用到的一個(gè)方法。不過(guò)這方面的內(nèi)容不是非常容易掌握,我們需要不斷的實(shí)踐積累才能充分了解其中的概念。
Ruby語(yǔ)言作為一種新興的編程語(yǔ)言,廣大編程語(yǔ)言都對(duì)其保佑非常大的好奇心。在這篇文章中我們將會(huì)認(rèn)識(shí)到Ruby重載的一些知識(shí)。#t#
在子類里,我們可以通過(guò)Ruby重載父類方法來(lái)改變實(shí)體的行為.
- ruby> class Human
- | def identify
- | print "I'm a person.\n"
- | end
- | def train_toll(age)
- | if age < 12
- | print "Reduced fare.\n";
- | else
- | print "Normal fare.\n";
- | end
- | end
- | end
- nil
- ruby> Human.new.identify
- I'm a person.
- nil
- ruby> class Student1<Human
- | def identify
- | print "I'm a student.\n"
- | end
- | end
- nil
- ruby> Student1.new.identify
- I'm a student.
- nil
如果我們只是想增強(qiáng)父類的 identify 方法而不是完全地替代它,就可以用 super進(jìn)行Ruby重載.
- ruby> class Student2<Human
- | def identify
- | super
- | print "I'm a student too.\n"
- | end
- | end
- nil
- ruby> Student2.new.identify
- I'm a human.
- I'm a student too.
- nil
super 也可以讓我們向原有的方法傳遞參數(shù).這里有時(shí)會(huì)有兩種類型的人...
- ruby> class Dishonest<Human
- | def train_toll(age)
- | super(11) # we want a
cheap fare.- | end
- | end
- nil
- ruby> Dishonest.new.train_toll(25)
- Reduced fare.
- nil
- ruby> class Honest<Human
- | def train_toll(age)
- | super(age) # pass the
argument we were given- | end
- | end
- nil
- ruby> Honest.new.train_toll(25)
- Normal fare.
- nil
以上就是對(duì)Ruby重載的相關(guān)知識(shí)介紹。
責(zé)任編輯:曹凱
來(lái)源:
jb51.net