Search code examples
arraysrubyloopsgets

Trying to create an array from input whilst in a loop - Ruby


I am trying to create a programme that asks the user for a number, the programme keeps asking the user for a number until "stop" is entered at which point the sum of the numbers is returned.

The code sort of works but I realise that the first puts/gets.chomp is outside of the loop and is not being added to the array. I dont know how to implement this, any help thoughts would be greatly appreciated!

array = []

puts 'Give me a number'

answer = gets.chomp

until answer == "stop"
  puts 'Give me a number'
answer = gets.chomp
  array.push(answer)
end

array.pop

array

Solution

  • You have a situation like this.

    do something
    determine if we should stop
    do something else
    repeat
    

    For this sort of fine control use a loop to repeat until you break.

    # Initialize your list of numbers.
    numbers = []
    
    # Start a loop.
    loop do
      # Get the answer.
      puts 'Give me a number'
      answer = gets.chomp
    
      # Stop if the user wants to stop.
      break if answer == 'stop'
    
      # Store the number after checking that it is a number.
      numbers.push(answer)
    end
    
    p numbers