On Aug 7, 2009, at 12:50 PM, chutsu wrote:

> I've got a file that is in two columns, how do I add the second column
> up as I read through the file?
>
> Code:
> #!/usr/bin/ruby
> file = File.open('some_file.txt')

total = 0 # make the variable have scope outside the block

> # Going through each line
> file.each do |line|
>  data = line.split("\t")
>  total += data[1]        # How do I make this line work?
# and convert the string to a numeric depending on what you expect
total += data[1].to_f
total += data[1].to_i
> end
>
> puts total
>


Or you could:

puts File.readlines('some_file.txt').inject(0) {|total,line| total +  
line.split("\t")[1].to_i }

(but if the file is large, that could be terribly inefficient)

-Rob

Rob Biedenharn		http://agileconsultingllc.com
Rob / AgileConsultingLLC.com