你離這本書第一部分的結尾已經不遠了,你應該已經具備了足夠的 Ruby 基礎知識,可以繼續學習一些程式的原理了,但你應該做更多的練習。這個練習的內容比較長,它的目的是鍛煉你的毅力,下一個習題也差不多是這樣的,好好完成它們,做到完全正確,記得仔細檢查。
~~~
puts "Let's practice everything."
puts "You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs."
poem = <<MULTI_LINE_STRING
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
MULTI_LINE_STRING
puts "--------------"
puts poem
puts "--------------"
five = 10 - 2 + 3 - 6
puts "This should be five: #{five}"
def secret_formula(started)
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
end
start_point = 10000
beans, jars, crates = secret_formula(start_point)
puts "With a starting point of: #{start_point}"
puts "We'd have #{beans} beans, #{jars} jars, and #{crates} crates."
start_point = start_point / 10
puts "We can also do that this way:"
puts "We'd have %s beans, %s jars, and %s crates." % secret_formula(start_point)
~~~
## 你應該看到的結果
~~~
$ ruby ex24.rb
Let's practice everything.
You'd need to know 'bout escapes with \ that do
newlines and tabs.
--------------
The lovely world
with logic so firmly planted
cannot discern
the needs of love
nor comprehend passion from intuition
and requires an explanation
where there is none.
--------------
This should be five: 5
With a starting point of: 10000
We'd have 5000000 beans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crates.
$
~~~
## 加分習題
1. 記得仔細檢查結果,從後往前倒著檢查,把程式碼朗讀出來,在不清楚的位置加上註釋。
2. 故意將程式碼改爛,執行並檢查會發生什麼樣的錯誤,並且確認你有能力改正這些錯誤。
- 笨方法更簡單
- 習題 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: 創造你的網頁游戲
- 下一步
- 一個老程式設計師的建議