How would I be able to make my program keep asking the user for a valid file name if the input they enter is not a valid file name? This is my current code:
print "What is the name of the input file that contains the list of students to be grouped: "
input_file = gets.chomp
if (File.exist?(input_file))
puts "this is a valid file"
else
puts "this is not valid"
end
CodePudding user response:
To keep asking the user to provide an input until your condition (file exists) is met, you will have to make use of a loop. There are various you could use, here is an example using until
, starting from the code you've provided.
puts "What is the name of the input file that contains the list of students to be grouped: "
input_file = gets.chomp
until File.exist?(input_file)
puts "this is not valid"
puts "What is the name of the input file that contains the list of students to be grouped: "
input_file = gets.chomp
end
puts "this is a valid file"
or another version to keep your code a bit more DRY
input_file = ''
until File.exist?(input_file)
puts "What is the name of the input file that contains the list of students to be grouped: "
input_file = gets.chomp
puts "this is not valid" if !File.exist?(input_file)
end
puts "this is a valid file"