Văn Khang Đinh
Văn Khang Đinh

Reputation: 85

Why can I not break from a `while` loop in ruby?

I don't understand why Ruby doesn't break from this while loop:

i = nil
while true
  i = gets
  if i == 5
    break
  end
  puts i
end

Please explain the reason.

Upvotes: 2

Views: 11578

Answers (1)

Sagar Pandya
Sagar Pandya

Reputation: 9497

Your code doesn't work because your loop is checking for i == 5, but gets will always return the user's input as a string. So if input is 5, gets will return it as "5", it won't convert it to 5 which is required for the break. You need to convert the input from a string to a number. Use String#to_i on your user input and your code will work as desired.

i = nil
while true
  i = gets.to_i
  if i == 5
    break
  end
  puts i
end

You could also introduce a second variable j used for checking if the input is 5 and to preserve i. This is so that if the user's input is a letter, the letter will be printed to the screen instead of 0:

while true
  i = gets.chomp
  j = i.to_i
  if j == 5
    break
  end
  puts i
end

Another way is to use a Kernel#loop:

loop do
  i = gets.chomp
  j = i.to_i
  break if j == 5
  puts i
end

Another way is to use an until loop:

j = 1
until j == 5
  i = gets.chomp
  j = i.to_i
  puts i
end

Upvotes: 8

Related Questions