I have this exercise where I must use a while loop to ask for info to the user and push it to an empty array. When the user doesn't write anything then the while loops stops.
I've tried setting the condition of the while loop with "" or empty? but nothing works. at this point I'm not sure if the problem is in the condition or the entire while loop
Help please
student_list = []
puts "add students to the wagon"
student = gets.chomp
while student.empty?
puts "add more students to the wagon"
student = gets.chomp
student_list << student
end
```
You have to use until
. Refer the following program
student_list = []
puts "add students to the wagon"
student = gets.chomp
until student.strip.empty?
puts "add more students to the wagon"
student = gets.chomp
student_list << student
end
Output
one
add more students to the wagon
two
add more students to the wagon
three
add more students to the wagon
This would work:
student_list = []
puts "add a student to the wagon"
student = gets.chomp
while !student.empty?
student_list << student
puts "add one more student to the wagon"
student = gets.chomp
end
student
while
loop checks that student
is not empty (hence the !
to invert the condition) student
to the arraystudent
(overwriting the previous value)Just another option using infinite loop and breaking:
student_list = []
while true
str = " more" if student_list.any?
puts "add#{str} students to the wagon"
student = gets.chomp
break if student.empty?
student_list << student
end
Instead of while true
you can just use loop do
, but this is beyond the assignment request.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.