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?
Hope this solves your problem :)
You can have a loop at the beginning to continuously ask for input until it's valid.
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 gettrue
for both empty and non-empty input. This means that this will always evaluate totrue
.