From: calderson Date: 2008-04-16T15:25:05+09:00 Subject: Re: Noob Questions [arrays] On Apr 15, 10:43 pm, Justin Collins wrote: > RoRNoob wrote: > > Be warned - I'm new to Ruby and programming in general, so I'm sure > > this will be a trivial question for most of you. > > > I'm currently working through the exercises in the book Learn to > > Program by Chris Pine. At the end of each chapter Chris has a little > > programming problem that the reader is asked to solve. I've been able > > to follow along just fine up until tonight. > > > The problem in question is at the end of Chapter 8 (Arrays and > > Iterators): I have to write a program that asks the user to type in as > > many words as they want (one word per line, continuing until they just > > press Enter on an empty line) and then repeat the words back to them > > in alphabetical order. > > > The program lives in a .rb file and is executed and ran from the > > terminal. > > > Here is my code: > > > alphalist = [] > > alphalist.each do |item| > > puts 'type words one at a time and I will alphabetize them for you.' > > alphalist.push gets.chomp > > end > > puts alphalist.sort > > > When I run the .rb file, nothing happens. Any help is appreciated! > > Take a look at your alphalist: it's just an empty array. When you do > alphalist.each, you are 'visiting' each item in the array, but there are > none. So it just skips down to 'puts alphalist.sort' and then exits. > > -Justin OK that helped - I'm able to get the array to load up and print out with this: alphalist = [''] alphalist.each do |item| puts 'type words one at a time and I will alphabetize them for you.' alphalist.push gets.chomp puts alphalist.sort end But now I can't figure out how to keep it from printing until the user enters an empty value. I've tried: alphalist = [''] alphalist.each do |item| puts 'type words one at a time and I will alphabetize them for you.' alphalist.push gets.chomp if gets == '' puts alphalist.sort end end ... it prints a gets value twice, then starts again with "type words one at a time and I will alphabetize them for you." If i hit enter it just puts a blank line.