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

如何正確實(shí)現(xiàn)Ruby創(chuàng)建可參數(shù)化類

開發(fā) 開發(fā)工具
Ruby創(chuàng)建可參數(shù)化類的實(shí)現(xiàn)對(duì)于剛剛接觸Ruby語(yǔ)言不久的朋友是一個(gè)比較難掌握的知識(shí),我們需要不斷的從實(shí)踐中去了解其中的含義。

Ruby語(yǔ)言在實(shí)際使用中會(huì)創(chuàng)建許多類,來(lái)滿足我們的整體編程需求。對(duì)于初學(xué)者來(lái)說(shuō),我們必須熟練地掌握創(chuàng)建類的方法,比如Ruby創(chuàng)建可參數(shù)化類等等。#t#

如果我們要?jiǎng)?chuàng)建很多類,這些類只有類成員的初始值不同,我們很容易想起:

  1. class IntelligentLife # Wrong 
    way to do this!   
  2. @@home_planet = nil   
  3. def IntelligentLife.home_planet   
  4. @@home_planet   
  5. end   
  6. def IntelligentLife.home_planet=(x)   
  7. @@home_planet = x   
  8. end   
  9. #...   
  10. end   
  11. class Terran < IntelligentLife   
  12. @@home_planet = "Earth"   
  13. #...   
  14. end   
  15. class Martian < IntelligentLife   
  16. @@home_planet = "Mars"   
  17. #...   
  18. end  

這種Ruby創(chuàng)建可參數(shù)化類方式是錯(cuò)誤的,實(shí)際上Ruby中的類成員不僅在這個(gè)類中被所有對(duì)象共享,實(shí)際上會(huì)被整個(gè)繼承體系共享,所以我們調(diào)用Terran.home_planet,會(huì)輸出“Mars”,而我們期望的是Earth一個(gè)可行的方法:

我們可以通過class_eval在運(yùn)行時(shí)延遲求值來(lái)達(dá)到目標(biāo):

  1. class IntelligentLife   
  2. def IntelligentLife.home_planet   
  3. class_eval("@@home_planet")   
  4. end   
  5. def IntelligentLife.home_planet=(x)   
  6. class_eval("@@home_planet = #{x}")   
  7. end   
  8. #...   
  9. end   
  10. class Terran < IntelligentLife   
  11. @@home_planet = "Earth"   
  12. #...   
  13. end   
  14. class Martian < IntelligentLife   
  15. @@home_planet = "Mars"   
  16. #...   
  17. end   
  18. puts Terran.home_planet # Earth   
  19. puts Martian.home_planet # Mars  

最好的Ruby創(chuàng)建可參數(shù)化類方法:

我們不使用類變量,而是使用類實(shí)例變量:

  1. class IntelligentLife   
  2. class << self   
  3. attr_accessor :home_planet   
  4. end   
  5. #...   
  6. end   
  7. class Terran < IntelligentLife   
  8. self.home_planet = "Earth"   
  9. #...   
  10. end   
  11. class Martian < IntelligentLife   
  12. self.home_planet = "Mars"   
  13. #...   
  14. end   
  15. puts Terran.home_planet # Earth   
  16. puts Martian.home_planet # Mars  

 

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

2010-01-06 15:56:18

.Net Framew

2009-12-08 14:31:31

PHP命令行讀取參數(shù)

2009-12-21 10:09:26

WCF創(chuàng)建客戶端服務(wù)對(duì)

2009-12-29 18:09:00

Silverlight

2010-02-25 10:10:29

WCF使用Header

2009-12-03 11:11:57

PHP網(wǎng)站優(yōu)化

2010-02-25 13:48:23

WCF動(dòng)態(tài)創(chuàng)建代碼

2009-12-11 17:52:21

PHP獲取博客數(shù)據(jù)

2009-12-07 18:42:55

PHP與Javascr

2009-12-04 12:51:27

PHP functio

2010-01-22 13:08:50

VB.NET創(chuàng)建數(shù)組

2009-12-09 16:49:09

PHP顯示文章發(fā)布時(shí)間

2010-04-29 17:31:56

Oracle存儲(chǔ)過程

2010-01-15 16:03:48

VB.NET重載Win

2010-03-04 15:12:33

Python算法

2010-03-04 11:12:02

Python AOP

2010-02-24 10:07:48

WCF跨越邊界

2020-10-15 10:51:05

云計(jì)算IT技術(shù)

2019-05-07 10:21:48

人工智能AI

2009-12-08 19:29:10

PHP生成唯一標(biāo)識(shí)符
點(diǎn)贊
收藏

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