函式這個概念也許承載了太多的資訊量。不過別擔心,只要堅持做這些練習題,對照上個練習中的檢查清單檢查這次練習的關聯,你最終會明白這些內容的。
有一個你可能沒有注意到的細節,我們現在強調一下,函式裡面的變數和腳本裡面的變數之間是沒有連接的。下面的這個練習可以讓你對這一點有更多的思考:
~~~
def cheese_and_crackers(cheese_count, boxes_of_crackers)
puts "You have #{cheese_count} cheeses!"
puts "You have #{boxes_of_crackers} boxes of crackers!"
puts "Man that's enough for a party!"
puts "Get a blanket."
puts # a blank line
end
puts "We can just give the function numbers directly:"
cheese_and_crackers(20, 30)
puts "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
puts "We can even do math inside too:"
cheese_and_crackers(10 + 20, 5 + 6)
puts "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
~~~
通過這個練習,你看到我們給我們的函式?`cheese_and_crackers`?很多的參數,然後在函式裡把他們印出來。我們可以塞數字、塞變數進去函式,我們甚至可以將變數和數學運算結合在一起。
從一方面來說,函式的參數和我們生成變數時用的?`=`?賦值符號類似。事實上,如果一個物件你可以用?`=`?將其命名,你通常也可以將其作為參數傳給一個函式。
## 你應該看到的結果
你應該研究一下腳本的輸出,和你想像的結果對比一下看有什麼不同。
~~~
$ ruby ex19.rb
We can just give the function numbers directly:
You have 20 cheeses!
You have 30 boxes of crackers!
Man that's enough for a party!
Get a blanket.
OR, we can use variables from our script:
You have 10 cheeses!
You have 50 boxes of crackers!
Man that's enough for a party!
Get a blanket.
We can even do math inside too:
You have 30 cheeses!
You have 11 boxes of crackers!
Man that's enough for a party!
Get a blanket.
And we can combine the two, variables and math:
You have 110 cheeses!
You have 1050 boxes of crackers!
Man that's enough for a party!
Get a blanket.
$
~~~
## 加分習題
1. 倒著將腳本讀完,在每一行上面添加一行註解,說明這行程式的作用。
2. 從最後一行開始,倒著閱讀每一行,讀出所有重要的符號來。
3. 自己邊寫出至少一個函式出來,然後用十種方法運行這個函式。
- 笨方法更簡單
- 習題 0: 準備工作
- 習題 1: 第一個程式
- 習題 2: 注釋和井號
- 習題 3: 數字和數學計算
- 習題 4: 變數(variable)和命名
- 習題 5: 更多的變數和印出
- 習題 6: 字串(string)和文字
- 習題 7: 更多印出
- 習題 8: 印出,印出
- 習題 9: 印出,印出,印出
- 習題 10: 那是什么?
- 習題 11: 提問
- 習題 12: 模組 (Module)
- 習題 13: 參數、解包、參數
- 習題 14: 提示和傳遞
- 習題 15: 讀取檔案
- 習題 16: 讀寫檔案
- 習題 17: 更多的檔案操作
- 習題 18: 命名、變數、程式碼、函式
- 習題 19: 函式和變數
- 習題 20: 函式和檔案
- 習題 21: 函式可以傳回東西
- 習題 22: 到現在你學到了哪些東西?
- 習題 23: 閱讀一些程式碼
- 習題 24: 更多練習
- 習題 25: 更多更多的練習
- 習題 26: 恭喜你,現在來考試了!
- 習題 27: 記住邏輯關系
- 習題 28: 布林(Boolean)表示式練習
- 習題 29: 如果(if)
- 習題 30: Else 和 If
- 習題 31: 做出決定
- 習題 32: 回圈和陣列
- 習題 33: While 回圈
- 習題 34: 存取陣列里的元素
- 習題 35: 分支 (Branches) 和函式 (Functions)
- 習題 36: 設計和測試
- 習題 37: 復習各種符號
- 習題 38: 閱讀程式碼
- 習題 39: 陣列的操作
- 習題 40: Hash, 可愛的 Hash
- 習題 41: 來自 Percal 25 號行星的哥頓人(Gothons)
- 習題 42: 物以類聚
- 習題 43: 你來制作一個游戲
- 習題 44: 評估你的游戲
- 習題 45: 物件、類和從屬關系
- 習題 46: 一個專案骨架
- 習題 47: 自動化測試
- 習題 48: 更進階的使用者輸入
- 習題 49: 創造句子
- 習題 50: 你的第一個網站
- 習題 51: 從瀏覽器中取得輸入
- 習題 52: 創造你的網頁游戲
- 下一步
- 一個老程式設計師的建議