加载中...

习题 24: 更多练习


你离这本书第一部分的结尾已经不远了,你应该已经具备了足够的 Ruby 基础知识,可以继续学习一些程式的原理了,但你应该做更多的练习。这个练习的内容比较长,它的目的是锻炼你的毅力,下一个习题也差不多是这样的,好好完成它们,做到完全正确,记得仔细检查。

  1. puts "Let's practice everything."
  2. puts "You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs."
  3. poem = <<MULTI_LINE_STRING
  4. \tThe lovely world
  5. with logic so firmly planted
  6. cannot discern \n the needs of love
  7. nor comprehend passion from intuition
  8. and requires an explanation
  9. \n\t\twhere there is none.
  10. MULTI_LINE_STRING
  11. puts "--------------"
  12. puts poem
  13. puts "--------------"
  14. five = 10 - 2 + 3 - 6
  15. puts "This should be five: #{five}"
  16. def secret_formula(started)
  17. jelly_beans = started * 500
  18. jars = jelly_beans / 1000
  19. crates = jars / 100
  20. return jelly_beans, jars, crates
  21. end
  22. start_point = 10000
  23. beans, jars, crates = secret_formula(start_point)
  24. puts "With a starting point of: #{start_point}"
  25. puts "We'd have #{beans} beans, #{jars} jars, and #{crates} crates."
  26. start_point = start_point / 10
  27. puts "We can also do that this way:"
  28. puts "We'd have %s beans, %s jars, and %s crates." % secret_formula(start_point)

你应该看到的结果

  1. $ ruby ex24.rb
  2. Let's practice everything.
  3. You'd need to know 'bout escapes with \ that do
  4. newlines and tabs.
  5. --------------
  6. The lovely world
  7. with logic so firmly planted
  8. cannot discern
  9. the needs of love
  10. nor comprehend passion from intuition
  11. and requires an explanation
  12. where there is none.
  13. --------------
  14. This should be five: 5
  15. With a starting point of: 10000
  16. We'd have 5000000 beans, 5000 jars, and 50 crates.
  17. We can also do that this way:
  18. We'd have 500000 beans, 500 jars, and 5 crates.
  19. $

加分习题

  1. 记得仔细检查结果,从后往前倒著检查,把程式码朗读出来,在不清楚的位置加上注释。
  2. 故意将程式码改烂,执行并检查会发生什么样的错误,并且确认你有能力改正这些错误。

还没有评论.