I’m a new guy with a question. Some background, started learning ruby 4
days ago, and I know nothing other that what I’ve picked up out of a
book I have. I found an exercise that I figured I’d try at the bottom of
http://www.evc-cit.info/cit020/beginning-programming/chp_04/file_printf.html

it looked fun so I tried it. I’d like some feedback from more
experienced guys. What would you have done different?

my code:

#iterate text into variable
text = ‘’

File.open(“scores.txt”).each do |x|
text << x
end

printf(“Name Average Score\n”)

#do math
def do_math(b)

sum = 0
x = b.gsub(“,”, " ")
nums = x.split(/\W/)
#puts nums[0,4]
loopnum = nums.size
arr_size = nums.size.to_i - 1

loopnum.times do |i|
sum = sum + nums[i].to_i
end
#printf(“equals – %i\n”, sum)
printf(“\t\t%3.2f\n”, sum/arr_size.to_f)
end

#handles individual lines
def compare(a)
x = a.size
name = a.gsub(/[0123456789,]/, “”)
printf("\n%s ", name)
garbage = “abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-”
nums = a.delete(garbage)
do_math(nums) #passes nums to do_math()
end

#split text to array
table = text.split(/\n/)
table_size = table.size

table_size.times do |i| #5 times
compare(table[i]) #pass a line to compare()
end

Here a solution:

=========================================
File.foreach(“foo.txt”) do |line|
name,scores=line.strip.split(/\s,\s*/)
next unless name && scores.size>0

# sum=scores.inject(0) {|sum,v| sum+=v.to_i} average=1.0*sum/scores.size puts “%-20s %5.2f” % [name,average] end

with
a=<<EEND
Steven,940,885,955
Federico,1000,1025,985
Chong-Ki,890,930,950
Margie,960,980,790
Reza,940,890,920
EEND
File.write(“foo.txt”,a)