Reputation: 45
I am trying to grab large numbers from a file, store them as an array, and add them up.
nums = Array.new
x, total=0, 0
file = File.open("inputfile.txt", 'r')
while !file.eof?
nums[x] = file.readline
x+=1
end
while x>0
x-=1
total += nums[x]
end
puts total
When my code executes, I get an error saying:
String can't be coerced into Fixnum (TypeError)
I checked to make sure that each array element actually has the right data in it. I think that the numbers are considered strings when stored. If that's the case, how would I change the array to integers so I can total them up?
Upvotes: 3
Views: 1459
Reputation: 160631
Here's how I'd do it:
total = 0
File.foreach("inputfile.txt") { |li| total += li.to_i }
puts total
Storing a large array in memory isn't a good idea because you can fill your available memory before your code can calculate a sum. Instead, read the file line-by-line and calculate as you go.
Benchmarks show that line-by-line I/O is as fast as reading an entire file into memory and then trying to process it as single lines, so use the more conservative IO.foreach
or ios.each_line
to avoid filling memory needlessly.
Upvotes: 1
Reputation: 42421
You can iterate line-by-line over an opened file:
total = File.open("inputfile.txt").inject(0) { |sum, line| sum + line.to_i }
Also see the example in the comment from squiguy, using map
and reduce
.
Upvotes: 1
Reputation: 120
Just modify
nums[x] = file.readline
to
nums[x] = file.readline.to_i
Cheers!
Upvotes: 4