Topic: Storing 'gets' Input In An Array

Hi all,

Ruby noob here learning the ropes. I'm currently going through this tutorial;
http://pine.fm/LearnToProgram/?Chapter=07

And am working on this exercise;
Let's write a program which asks us to type in as many words as we want (one word per line, continuing until we just press Enter on an empty line), and which then repeats the words back to us in alphabetical order.

I'm ignoring the alphabetical order part, for now.

Here is my code;
puts 'Hi, do you need something sorted?'
yn = gets.chomp
while yn != 'no'
puts 'What else?'
array = [gets]
yn = gets.chomp
end
puts 'Here\'s what you told me: ' +array.to_s

I've tweaked this for a few hours. To prevent my laptop from breaking due to an act of frustration I'm taking a break. Can anybody with more experience, and possibly more patience, point out my errors?

Last edited by RubyStn (2011-03-07 14:16:24)

Re: Storing 'gets' Input In An Array

Your array variable is in the while loop scope only, so you can not access to it outside the scope.
Try like that:

#STDIN.gets -use instead of gets if yu want to take/output the result from/to the console only
puts "Please enter the text"
array = []
while line = gets
  break if line.chomp =~ /N/ #exit when 'N' is entered
  puts "Entered: #{line.chomp}"
  array << line.chomp
end
puts "Finished with result: #{array.join('-')}" #joining all the elements with a hyphen

Last edited by Javix (2011-03-10 06:26:08)