The loop does not end when checking conditions

This loop does not end after entering x. I'm really new to Ruby, and so far it is very different from what I learned before - quite interesting,

total = 0
i = 0

while ((number = gets) != "x")
    total += number.to_i
    i += 1
end

puts  "\nAverage: " + (total / i).to_s

Any help is greatly appreciated.

+3
source share
1 answer

Because it getsgives you a new line. You need chompit.

Try:

while ((number = gets.chomp) != "x")

and you will see that it starts to work:

pax> ruby testprog.rb
1
5
33
x

Average: 13
+4
source

Source: https://habr.com/ru/post/1758134/


All Articles