0

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
3
  • 1
    Why do u need input before loop? You can just set answer = nil before loop and all must be fine Commented May 5, 2019 at 19:21
  • Welcome to SO! You're extremely close--I recommend trying to work it out the rest of the way! Commented May 5, 2019 at 19:23
  • Why are you using an array? Since the goal is to output the sum of the numbers, just start with sum = 0 and keep incrementing it by the input as long as the input is numeric. There's no need to store all the inputs. Commented May 5, 2019 at 22:37

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.