[英]How to check if gets.chomp is empty with ruby
我有這個練習,我必須使用 while 循環向用戶詢問信息並將其推送到一個空數組。 當用戶不寫任何東西時,while 循環就會停止。
我試過用“”或空設置while循環的條件? 但沒有任何作用。 在這一點上,我不確定問題出在條件還是整個 while 循環中
請幫忙
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
```
你必須使用until
。 參考以下程序
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
這會起作用:
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
循環檢查student
是否為空(因此使用!
來反轉條件)student
添加到數組中student
(覆蓋以前的值)使用無限循環和中斷的另一種選擇:
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
而不是while true
你可以只使用loop do
,但這超出了分配請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.