maryanne maryanne - 9 months ago 25
Ruby Question

Making a sorted array of user's input

I'm learning Ruby with 'Learn to Program' by Chris Pine. On chapter 10 I should write a program where the user types as many words as he like and when he's done, he can just press

on an empty line and exit.
I came up with this:

puts "Type whatever you want!"
index = 0
word = ''
array = []
while word != nil
word << gets.chomp
array[index] = word
index = index + 1
puts ''
puts array.sort

But that doesn't work. What did I miss? Is there another way I could define
without having to repeat it?


The word will not have nil value. It will be an empty string. So you need to check for that:

while word != ""

# or even better
while !word.empty?

Also, you are adding everything to your word. You probably want to assign to it instead:

word = gets.chomp

Per author's comment:

  # your code here 
end while !word.empty?

# OR more readable
  # your code here 
end until word.empty?