简体   繁体   中英

How to check if gets.chomp is empty with ruby

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
  1. you start by reading the first name and assign it to student
  2. the while loop checks that student is not empty (hence the ! to invert the condition)
  3. within the loop, you add student to the array
  4. you read the next name and assign it to student (overwriting the previous value)
  5. end of loop, move up to 2.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM