如何使用回车键退出红宝石的while循环

问题描述

我正在尝试编写一个程序,该程序不断将用户输入添加到数组中,直到他们在空行上按回车键为止。然后,它将按字母顺序对数组进行排序,并向您显示排序后的数组。这不是让我突围。 这是我的代码

wordList = []
puts "enter as many words as you like"
entry = gets.chomp
while true
    wordList.push entry
    if entry == ''
        break
    end
end
sortedWordList = wordList.sort
puts sortedWordList

解决方法

您可以执行以下操作:

wordList = []
puts "Enter as many words as you like:\n"
while (entry = gets.chomp)
  break if entry.empty?
  wordList.push entry
end
puts wordList.sort
,
wordList = []
puts "enter as many words as you like"
while true
  entry = gets.chomp
  wordList << entry
  if entry.blank?
    break
  end
end
sortedWordList = wordList.sort
puts wordList.inspect
puts sortedWordList

您将获得类似以下内容的输出

$ ruby test.rb
enter as many words as you like
d
f
g
h
y
a
b
c
j
k

["d","f","g","h","y","a","b","c","j","k",""]

a
b
c
d
f
g
h
j
k
y
,

如果将代码entry = gets.chomp向下移动到while true下方,则您的代码可以正常工作。现在正在做的是将第一个条目无限地添加到wordList中。

这是在保持可读性的同时缩短它的一种方法:

words = []
puts "enter as many words as you like"
until (entry = gets.chomp) == ""
  words << entry
end