1

Writing a ruby while loop that take integers as an input and stores them in an array when a certain integer is entered (-1) the loop should stop and print out the array. When -1 is entered the loop stops but there is no output.

puts " Enter a number"

x = -1.to_i
number = ' '
numbers = []

while number != x
    number = gets.chomp
    numbers.push(number)
  end


puts
numbers.pop
p numbers
1
  • "When -1 is entered the loop stops ..." – with the given code, it will just keep looping. Commented Dec 23, 2020 at 15:03

1 Answer 1

1

The loop will never stop gets.chomp returns a String so the loop will go on for ever because:

"-1" != -1 
#=> true

Try changing this to:

while number != x
  number = gets.chomp.to_i
  numbers.push(number)
end
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.