From: Tim Hunter Date: 2009-08-29T05:57:02+09:00 Subject: Re: Error with an array of strings Tom Smith wrote: > Hi, > This is clearly a Ruby beginner question, so please be nice :) > > This program is supposed to take user input of numbers and average the > numbers. I figured I'd create a loop, an array, and then average the > numbers by dividing by the total length of the array. > > #Get numbers > total = [ ] > > until $_ == "n" > puts "Enter Number:\n" > number = STDIN.gets > number.chop! > number.to_i > > total.push(number) #puts all the numbers into the array > > print "add more numbers to average? y or n\n" > continue = STDIN.gets > continue.chop! > > end > > #Compute Average > > all = total.slice(0..total.length) #slices the array no matter how large > it is > > averageall = [all.slice(0..total.length)] / total.length > > puts "Average is:", averageall,"\n" > > Needless to say, I'm getting an error with the averageall, since (I > assume) it's trying to divide by strings. I figure I need to convert the > array of strings to an array of integers. Alas, I can't seem to track > down the correct solution. Any help would be much appreciated for this > newbie to Ruby. > > Thanks. The to_i method converts a string to an integer, assuming the string really can be so converted. "1".to_i => 1 ["1", "2", "3"].map {|d| d.to_i} => [1, 2, 3] -- MagickWand for Ruby - http://magickwand.rubyforge.org/