tags:

views:

34

answers:

1

This loop does not terminate after I type x. I'm really new to Ruby, and so far, it is so much different than 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  A: 

Because gets gives you the newline as well. You need to chomp it.

Try:

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

and you'll see it starts working:

pax> ruby testprog.rb
1
5
33
x

Average: 13
paxdiablo
Work perfectly! Thank you!
skynorth