昊天SEO

练习31: 做出决定–笨方法学ruby在线

这本书的上半部分,你打印出了一些东西,并且调用了函式,不过一切都是直线式进行的。你的脚本从最上面一行开始,一路运行到结束,但其中并没有决定程序流向的分支点。现在你已经学会了 if、else和 elsif,你就可以开始建立包含条件判断的脚本了。
上一个脚本中你写了一系列的简单提问测试。这节的脚本中,你将需要向使用者提问,依据使用者的答案来做出决定。把脚本写下来,多多捣鼓一阵子,看看他的运作原理是什么。

def prompt
  print "> "
end

puts "You enter a dark room with two doors.  Do you go through door #1 or door #2?"

prompt; door = gets.chomp

if door == "1"
  puts "There's a giant bear here eating a cheese cake.  What do you do?"
  puts "1. Take the cake."
  puts "2. Scream at the bear."

  prompt; bear = gets.chomp

  if bear == "1"
    puts "The bear eats your face off.  Good job!"
  elsif bear == "2"
    puts "The bear eats your legs off.  Good job!"
  else
    puts "Well, doing #{bear} is probably better.  Bear runs away."
  end

elsif door == "2"
  puts "You stare into the endless abyss at Cthuhlu's retina."
  puts "1. Blueberries."
  puts "2. Yellow jacket clothespins."
  puts "3. Understanding revolvers yelling melodies."

  prompt; insanity = gets.chomp

  if insanity == "1" or insanity == "2"
    puts "Your body survives powered by a mind of jello.  Good job!"
  else
    puts "The insanity rots your eyes into a pool of muck.  Good job!"
  end

else
  puts "You stumble around and fall on a knife and die.  Good job!"
end

未经允许不得转载:新乡seo|网站优化,网站建设—昊天博客 » 练习31: 做出决定–笨方法学ruby在线

网站的维护离不开大家的支持鼓励,捐赠让我更有动力走的更远&& 也可以关注我的微信公众号,发布更多的干货
本文网址:https://www.168seo.cn/ruby/rubyben/2295.html

相关推荐