Brian Ruff Brian Ruff - 2 months ago 9
Ruby Question

Add information to an array

I'm trying to write a program that asks users to enter words, and then I want the words entered to be stored into an array which is later to be printed on the screen after they press the return key.

Here is the code logic I am using now, but I'm just struggling to figure this out.

while loop do
puts "Enter your words: "
user_input = gets.chomp.capitalize
if user_input != ""
user_words =
user_input.push user_words
elsif user_input == ""
puts user_words.to_s

Answer Source

There are many problems with your code, here they are:

  1. Having while and loop in one statement is useless
  2. puts 'Enter your words:' should be declared outside of the loop
  3. user_words should be declared outside of the loop to accumulate the values
  4. puts user_words.to_s should be outside of the loop to print all values in the very end
  5. push should be called on an array not on a string
  6. elsif user_input == "" is excessive, could be replaced with else
  7. is worse than []

Here is my solution:

puts 'Enter your words:'

words = []

loop do
  input = gets.chomp.capitalize
  break if input == ''
  words << input

puts words.to_s

I hope it helps.