How to re-prompt and re-use a user's input

2019-09-20 14:38发布

I was trying to re-prompt a user's input and reuse it. Here's the code sample:

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}!"

My elsif will let the user know that their input was not acceptable, but was not effective in re-using their input to start from the beginning. How am I supposed to do it? Should I use a while or for loop?

3条回答
我命由我不由天
2楼-- · 2019-09-20 15:02

Hope this solves your problem :)

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
查看更多
ら.Afraid
3楼-- · 2019-09-20 15:04
  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}!"
查看更多
Root(大扎)
4楼-- · 2019-09-20 15:06

You can have a loop at the beginning to continuously ask for input until it's valid.

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

This will continuously ask for input until user_input.include? "" returns false. This way, you don't have to validate input later.

However, I'm not sure what you are trying to do here. If you want to re-prompt when the input is empty, you can just use the condition user_input == "".

EDIT: Here's the doc for String.include?. I tried running .include? "" and I get true for both empty and non-empty input. This means that this will always evaluate to true.

查看更多
登录 后发表回答