字母顺序代码在我的排序数组中留下了多余的“”“

时间:2016-01-26 17:22:47

标签: arrays ruby sorting

为什么以下代码在我的最终数组中留下了额外的""

puts 'Type in as many words as you\'d like. When you\'re finished, press enter on an empty line'
array = []
input = ' '
while input != ''
  input = gets.chomp
  array.push input
end
array.sort

2 个答案:

答案 0 :(得分:1)

无论是否存在,都将input推送到数组上。由于您要检查读取和推送之间的终止条件,因此这是使用break的好地方:

puts 'Type in as many words as you\'d like. When you\'re finished, press enter on an empty line'
array = []
loop do
  input = gets.chomp
  break if input.empty?
  array.push input
end
puts
puts array.sort

答案 1 :(得分:0)

正如斯特凡在评论中提到的那样,因为你总是推动你得到的东西。

你应该在循环中交换这两个方法,以便检查gets和push之间的条件。

puts 'Type in as many words as you\'d like. When you\'re finished, press enter on an empty line'
array = []
input = gets.chomp
until input.empty?
  array.push input
  input = gets.chomp
end