Reputation: 3
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
Upvotes: 0
Views: 654
Reputation: 164829
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
Upvotes: 2