我这里有个小问题!
如何确保 Ruby 创建新的 .txt 文档,其信息与终端显示的信息完全相同?
为了更清楚,我有,例如,这个脚本:
class GradeCalculator
@@new = {}
def initialize( file )
@file_data = { }
File.open( file ) do |file|
file.each_line do |line|
line_data = line.split( "," )
@file_data[ line_data[ 0 ] ] = line_data[ 1 ].to_i
end
end
end
def maximumgrade( )
@file_data.each do |k, v|
if v == @file_data.values.max
return v
end
end
end
def change( )
@high = maximumgrade( )
@file_data.map do |k,v|
if v != 0
@file_data[ k ] = 100 * v / @high
@@new = @file_data
end
end
end
def GradeCalculator.show
puts " \nExam is passed by:\n"
@@new.each{ |k,v| puts "#{k}, #{v}% (grade A+)" if v >= 97}
@@new.each{ |k,v| puts "#{k}, #{v}% (grade A)" if v<97 and v>=93}
@@new.each{ |k,v| puts "#{k}, #{v}% (grade B)" if v < 93 and v >= 85}
@@new.each{ |k,v| puts "#{k}, #{v}% (grade C)" if v < 85 and v >= 77}
@@new.each{ |k,v| puts "#{k}, #{v}% (grade D)" if v < 77 and v >= 70}
@@new.each{ |k,v| puts "#{k}, #{v}% (grade F)" if v < 70 and v >= 50}
puts " \n\n\nExam is failed by:\n"
@@new.each{|k,v| puts "#{k}, #{v}% (grade F)" if v < 50}
end
end
new = GradeCalculator.new( './Documents/ruby/grades/examresults.txt' )
new.maximumgrade( )
new.change( )
GradeCalculator.show
File.open("newmarks.txt", "w") do |f|
f.write(GradeCalculator.show)
end
我希望“newmarks.txt”完全包含
Exam is passed by:
Dora Bailey, 100% (grade A+)
Mathias Abbot, 82% (grade C)
Matt Dalton, 82% (grade C)
Paul Larson, 84% (grade C)
John Cameron, 75% (grade D)
Tiago Zimmerman, 73% (grade D)
Marcus Weinstein, 76% (grade D)
Patrick Kendall, 76% (grade D)
Jesus Bagwell, 50% (grade F)
Erika Galvan, 68% (grade F)
Manuel Sanchez, 65% (grade F)
Charles Radner, 66% (grade F)
Niraj Jarvis, 63% (grade F)
Eva Keefe, 60% (grade F)
Jessie Quaid, 60% (grade F)
Silvia Young, 57% (grade F)
Rosa Gall, 50% (grade F)
Exam is failed by:
Marta Alvarez, 46% (grade F)
Peter Anders, 34% (grade F)
Ben Lawrence, 0% (grade F)
Ana Osborne, 42% (grade F)
Jose Torres, 46% (grade F)