自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Ruby重載知識(shí)講解

開(kāi)發(fā) 開(kāi)發(fā)工具
Ruby重載在實(shí)際編程中是非常常用到的一個(gè)方法。不過(guò)這方面的內(nèi)容不是非常容易掌握,我們需要不斷的實(shí)踐積累才能充分了解其中的概念。

Ruby語(yǔ)言作為一種新興的編程語(yǔ)言,廣大編程語(yǔ)言都對(duì)其保佑非常大的好奇心。在這篇文章中我們將會(huì)認(rèn)識(shí)到Ruby重載的一些知識(shí)。#t#

在子類里,我們可以通過(guò)Ruby重載父類方法來(lái)改變實(shí)體的行為.

  1. ruby> class Human   
  2. | def identify   
  3. | print "I'm a person.\n"   
  4. | end   
  5. | def train_toll(age)   
  6. | if age < 12   
  7. | print "Reduced fare.\n";   
  8. | else   
  9. | print "Normal fare.\n";   
  10. | end   
  11. | end   
  12. | end   
  13. nil   
  14. ruby> Human.new.identify   
  15. I'm a person.   
  16. nil   
  17. ruby> class Student1<Human   
  18. | def identify   
  19. | print "I'm a student.\n"   
  20. | end   
  21. | end   
  22. nil   
  23. ruby> Student1.new.identify   
  24. I'm a student.   
  25. nil  

 

如果我們只是想增強(qiáng)父類的 identify 方法而不是完全地替代它,就可以用 super進(jìn)行Ruby重載.

  1. ruby> class Student2<Human   
  2. | def identify   
  3. | super   
  4. | print "I'm a student too.\n"   
  5. | end   
  6. | end   
  7. nil   
  8. ruby> Student2.new.identify   
  9. I'm a human.   
  10. I'm a student too.   
  11. nil   

 

super 也可以讓我們向原有的方法傳遞參數(shù).這里有時(shí)會(huì)有兩種類型的人...

  1. ruby> class Dishonest<Human   
  2. | def train_toll(age)   
  3. | super(11) # we want a 
    cheap fare.   
  4. | end   
  5. | end   
  6. nil   
  7. ruby> Dishonest.new.train_toll(25)   
  8. Reduced fare.   
  9. nil   
  10. ruby> class Honest<Human   
  11. | def train_toll(age)   
  12. | super(age) # pass the 
    argument we were given   
  13. | end   
  14. | end   
  15. nil   
  16. ruby> Honest.new.train_toll(25)   
  17. Normal fare.   
  18. nil   

 

以上就是對(duì)Ruby重載的相關(guān)知識(shí)介紹。

責(zé)任編輯:曹凱 來(lái)源: jb51.net
相關(guān)推薦

2009-12-15 11:01:31

Ruby數(shù)組

2009-12-15 14:58:19

Ruby迭代器

2009-12-16 14:24:48

Ruby函數(shù)lambd

2009-12-14 09:33:04

Ruby安裝

2009-12-17 15:11:47

Ruby百分號(hào)表示法

2009-12-14 15:30:43

安裝Ruby on R

2009-12-16 15:41:10

Ruby on Rai

2009-12-16 17:37:31

Ruby on Rai

2009-12-16 13:21:22

Ruby will_p

2009-12-18 14:35:01

Ruby奇特變量

2009-12-15 09:56:51

Ruby流程控制

2009-12-22 14:54:52

WCF安全

2010-05-05 13:13:55

Unix內(nèi)核

2009-12-15 13:26:33

Ruby單態(tài)方法

2010-05-04 09:22:10

Unix文件

2010-05-05 13:45:21

Unix Telnet

2010-04-30 13:27:26

Unix cronta

2010-05-04 12:25:28

Unix鏈接

2010-04-30 13:38:51

Unix at命令

2009-12-14 14:32:50

Ruby線程局部域變量
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)