【问题标题】:How to re-prompt and re-use a user's input如何重新提示和重用用户的输入
【发布时间】:2016-01-24 02:58:34
【问题描述】:

我试图重新提示用户的输入并重复使用它。这是代码示例:

print "Please put your string here!"

user_input = gets.chomp
user_input.downcase!

if user_input.include? "s"
  user_input.gsub!(/s/,"th")
elsif user_input.include? ""
  user_input = gets.chomp
  puts "You didn't enter anything!Please type in something."
  user_input = gets.chomp
else
  print "no \"S\" in the string"
end
puts "transformed string: #{user_input}!"

我的elsif 会让用户知道他们的输入是不可接受的,但在重新使用他们的输入从头开始时无效。我该怎么做?我应该使用while 还是for 循环?

【问题讨论】:

  • 我不知道你想做什么,但对于任何字符串ss.include? ""true
  • @sawa,你当然不知道,因为你没有问过他。

标签: ruby loops prompt


【解决方案1】:

希望这能解决你的问题:)

while true
  print 'Please put your string here!'
  user_input = gets.strip.downcase

  case user_input
    when ''
      next
    when /s/
      user_input.gsub!(/s/, "th")
      puts "transformed string: #{user_input}!"
      break
    else
      puts "no \"S\" in the string"
      break
  end
end

【讨论】:

  • 您好,非常感谢!有用!我只有一个关于next 方法的问题。是否意味着跳过上述条件并从顶部开始?而不是进入第二个条件?
  • 是的,'next' 跳过当前迭代的其余代码并开始下一个迭代。
  • 如果需要,可以省略 next
  • 对,你是@WayneConrad,因为案件之后没有其他声明
【解决方案2】:

你可以在开始时有一个循环来不断地请求输入,直到它有效为止。

while user_input.include? "" #not sure what this condition is meant to be, but I took it from your if block
    user_input = gets.chomp
    user_input.downcase!
end

这将持续要求输入,直到 user_input.include? "" 返回 false。这样,您以后不必验证输入。

但是,我不确定您要在这里做什么。如果想在输入为empty的时候重新提示,只要使用条件user_input == ""即可。

编辑Here's the doc 代表String.include?。我尝试运行.include? "",我得到true 用于空输入和非空输入。这意味着这将总是评估为true

【讨论】:

    【解决方案3】:
      user_input = nil    
      loop do
          print "Please put your string here!"
          user_input = gets.chomp
          break if user_input.length>0
      end
      user_input.downcase!
      if user_input.include? "s"
         user_input.gsub!(/s/,"th")      
      else
         puts "no \"S\" in the string"
      end
    
      puts "transformed string: #{user_input}!"
    

    【讨论】:

    • 如果没有任何解释,代码块看起来不太好。考虑添加一些
    • 我只是用“loop do”改变循环部分。首先,我使用“loop do”,因为我用 nill 值启动 user_input,所以“loop do”仍然执行一次。它将循环直到用户输入一个或多个输入,其余相同
    猜你喜欢
    • 1970-01-01
    • 2013-12-12
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多