簡體   English   中英

如何使用 ruby 檢查gets.chomp 是否為空

[英]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
  1. 您首先閱讀名字並將其分配給student
  2. while循環檢查student是否為空(因此使用!來反轉條件)
  3. 在循環中,您將student添加到數組中
  4. 您讀取下一個名稱並將其分配給student (覆蓋以前的值)
  5. 循環結束,移動到 2。

使用無限循環和中斷的另一種選擇:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM