maryanne maryanne - 7 months ago 10
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

Enter
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
end
puts ''
puts array.sort


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

Answer

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:

begin 
  # your code here 
end while !word.empty?

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