Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do You Put 'gets' Input Into An Array?

Tags:

arrays

ruby

Ruby noob here learning the ropes. I'm currently going through this tutorial 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?

like image 567
RubyStn Avatar asked Dec 13 '22 15:12

RubyStn


2 Answers

Keep in mind that every time you gets is a method that asks the user for input. On your lines:

array = [gets]
yn = gets.chomp

You are actually asking for input twice. Instead, store the user input somewhere (such as the array, see below) and get the stored value rather than asking the user twice.

Further, array = [gets] replaces the existing array with an array containing one element (the user input). You are never building up user input into the array. Instead, initialize the array before the while loop and use << in the loop:

array = Array.new
...
while yn != "no"
  ...
  array << gets.chomp
  yn = array.last
  ...
end
like image 156
Martin Gordon Avatar answered Jan 10 '23 05:01

Martin Gordon


If you're having difficulty with something, the first thing you should do is try something simpler.

Rather than doing gets and looping, just try doing a simple gets.

puts 'Hi, do you need something sorted?'
yn = gets.chomp

Then I'd see if yn was what I expected.

The next thing I'd do is, rather than doing a loop many times, just try it once

puts 'Hi, do you need something sorted?'
yn = gets.chomp
if yn != 'no'
  puts 'What else?'
  array = [gets]
  yn = gets.chomp
  STDERR.puts "array is #{array.inspect}"
  STDERR.puts "yn is #{yn.inspect}"
end

Then you'd hopefully realize that array and yn are both getting input, which wouldn't make sense.

For more hints on how to debug Ruby code, see How do I debug Ruby scripts?

like image 34
Andrew Grimm Avatar answered Jan 10 '23 05:01

Andrew Grimm