加载中...

习题 14: 提示和传递


让我们使用 ARGV 和 gets.chomp 一起来向使用者提一些特别的问题。下一节习题你将会学习到如何读写档案,这节习题是下节的基础。在这道习题里我们将用一个简单的 > 作为提示符号。这和一些游戏中的方法类似,例如 Zork 或者 Adventure 这两款游戏。

  1. user = ARGV.first
  2. prompt = '> '
  3. puts "Hi #{user}, I'm the #{$0} script."
  4. puts "I'd like to ask you a few questions."
  5. puts "Do you like me #{user}?"
  6. print prompt
  7. likes = STDIN.gets.chomp()
  8. puts "Where do you live #{user}?"
  9. print prompt
  10. lives = STDIN.gets.chomp()
  11. puts "What kind of computer do you have?"
  12. print prompt
  13. computer = STDIN.gets.chomp()
  14. puts <<MESSAGE
  15. Alright, so you said #{likes} about liking me.
  16. You live in #{lives}. Not sure where that is.
  17. And you have a #{computer} computer. Nice.
  18. MESSAGE

注意到我们将用户提示符号设置为 prompt,这样我们就不用每次都要重打一遍了。如果你要将提示符号和修改成别的字串,你只要改一个地方就可以了。

非常顺手吧。

Important: 同时必须注意的是,我们也用了 STDIN.gets 取代了 gets。这是因为如果有东西在 ARGV 里,标准的gets 会认为将第一个参数当成档案而尝试从里面读东西。在要从使用者的输入(如stdin)读取资料的情况下我们必须明确地使用 STDIN.gets

你应该看到的结果

当你执行这个脚本时,记住你需要把你的名字传给这个脚本,让 ARGV 可以接收到。

  1. $ ruby ex14.rb Zed
  2. Hi Zed, I'm the ex14.rb script.
  3. I'd like to ask you a few questions.
  4. Do you like me Zed?
  5. > yes
  6. Where do you live Zed?
  7. > America
  8. What kind of computer do you have?
  9. > Tandy
  10. Alright, so you said 'yes' about liking me.
  11. You live in 'America'. Not sure where that is.
  12. And you have a 'Tandy' computer. Nice.

加分习题

  1. 查一下 Zork 和 Adventure 是两个怎样的游戏。看能不能抓到,然后玩玩看。
  2. 将 prompt 变量改为完全不同的内容再执行一遍。
  3. 给你的脚本再新增一个参数,让你的程式用到这个参数。
  4. 确认你弄懂了我如何结合 <<SOMETHING 形式的多行字串与 #{} 字串注入做的印出。

还没有评论.