
基本的設計如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | class Encrypt def setCode @code = Array ( 'a' .. 'z' ).shuffle end def getCode @code .join end def toEncode "toEncode" end def toDecode "toDecode" end end e = Encrypt.new e.setCode puts puts e.getCode puts e.toEncode puts e.toDecode puts = begin 《程式語言教學誌》的範例程式 檔名:encrypt.rb 功能:示範 Ruby 程式 作者:張凱慶 時間:西元 2012 年 12 月 = end |
我們定義四個方法 (method) ,第一個方法 setCode 用來設定密碼表。留意此時變數 (variable) @code 要用實體變數 (instance variable) ,這樣才能用在 Encrypt 中的其他方法
2 3 4 | def setCode @code = Array ( 'a' .. 'z' ).shuffle end |
第二個方法 getCode 用來取得密碼表 @code ,這可以讓我們在類別以外的地方取得密碼表。由於 @code 為陣列 (array) ,這裡使用陣列的 join 方法將 @code 連結成一個字串 (string)
6 7 8 | def getCode @code .join end |
join 的預設參數 (parameter) 為 sep = "" ,因此沒有額外設定 sep 的話,陣列中的元素就以 "" 連接在一起。
其餘兩個 toEncode 與 toDecode 是用來編碼與解碼的,這裡先寫出來
10 11 12 13 14 15 16 | def toEncode "toEncode" end def toDecode "toDecode" end |
底下我們寫了一小段測試目前 Encrypt 類別的程式
19 20 21 22 23 24 25 | e = Encrypt.new e.setCode puts puts e.getCode puts e.toEncode puts e.toDecode puts |
執行結果如下

雖然測試程式可以和類別定義都放在同一個檔案裡,可是這不是一個好的設計習慣,因為我們設計 Encrypt 類別的目的就是作為一個可以一再重複使用的類別,如果每個程式檔案都得重複放 Encrypt 的定義就真的太麻煩了。我們應該就只把 Encrypt 放在 encrypt.rb 裡,然後給其他程式檔案 require 唷!
中英文術語對照 | |
---|---|
類別 | class |
方法 | method |
變數 | variable |
實體變數 | instance variable |
陣列 | array |
字串 | string |
參數 | parameter |
您可以繼續參考
軟體開發
相關目錄
回 Ruby 入門指南
回 Ruby 教材
回首頁
參考資料
http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html
http://www.ruby-doc.org/docs/ProgrammingRuby/html/classes.html
http://www.rubyist.net/~slagell/ruby/oothinking.html
http://www.rubyist.net/~slagell/ruby/classes.html
沒有留言:
張貼留言