问题
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?
回答1:
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
回答2:
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
.
回答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}!"
来源:https://stackoverflow.com/questions/34971716/how-to-re-prompt-and-re-use-a-users-input