【问题标题】:Ruby Loops with GrandmaRuby Loops 与祖母
【发布时间】:2011-04-22 02:32:56
【问题描述】:

好的,我正在尝试编写我祖母的红宝石模拟。我不能完全让循环按照我想要的方式工作。我要奶奶回应

“哦,这让我想起了(随机年份)……”

当你用大写字母回答她但我也希望她回应

“你说什么????”

当您不使用全部大写时。我可以让每个人单独工作,但我似乎无法用她疯狂的反应让奶奶连续循环。代码如下:

puts 'HELLO SONNY! WHAT\'S NEW IN THE WHO\'S IT WHAT\'S IT?'
response = gets.chomp

while response == response.upcase
  puts 'OH, THAT REMINDS ME OF BACK IN ' + (rand(50) + 1905).to_s + '...'
  response = gets.chomp
end

while response != response.upcase
  puts 'WHAT\'D YOU SAY????'
  response = gets.chomp
end

有什么想法吗?

【问题讨论】:

  • 既然您显然刚刚开始学习 Ruby(我从同一个教程开始),我只想指出,如果您使用双引号 "" 代替,您不必转义字符串中的字符的单引号。在这样的简单情况下很方便。

标签: ruby loops while-loop


【解决方案1】:

问题在于,一旦退出第一个 while 循环,就再也不会返回它了。试试这样的:

while true
  response = gets.strip
  if response == response.upcase
     puts msg1
  else
     puts msg2
  end
end

这将永远运行,直到你决定用 Ctrl-C 杀死虚拟奶奶。

【讨论】:

  • 太好了,解决了她的问题!在 .chomp 上使用 .strip 有什么好处吗?
  • 我喜欢它,因为它可以处理任何类型的前导和尾随空格,其中 chomp 只是拉断尾随换行符。不过,在这种情况下,您也不需要。
  • 您可以将while true 替换为while response = gets.strip
【解决方案2】:

这个程序有效,虽然我是菜鸟,所以它可能不是最好的方法。而且我的数学比实用更有创意,其他人要好得多。 :)

puts 'Talk to your grandma!'

while true
  say = gets.chomp

  if say == say.downcase
   puts 'WHAT DID YOU SAY? SPEAK UP!'

  else say == say.upcase
   puts "NO HONEY, NOT SINCE 19" + (rand(90) + 10).to_s 

  end

  break if say == 'bye'.upcase

end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 2011-01-23
    • 2015-09-27
    • 2017-01-02
    相关资源
    最近更新 更多