0

我这里有个小问题!

如何确保 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)
4

1 回答 1

1

您希望该GradeCalculator.show方法返回一个字符串而不是输出它。与您的show方法相比,最简单的变化是:

def GradeCalculator.show 
  @@new.inject(" \nExam is passed by:\n\n") do |out, (k,v)|
    out + "#{k}, #{v}% (grade A+)\n" if v >= 97 
    out + "#{k}, #{v}% (grade A)\n" if v < 97 and v >= 93
    out + "#{k}, #{v}% (grade B)\n" if v < 93 and v >= 85 
    out + "#{k}, #{v}% (grade C)\n" if v < 85 and v >= 77
    out + "#{k}, #{v}% (grade D)\n" if v < 77 and v >= 70
    out + "#{k}, #{v}% (grade F)\n" if v < 70 and v >= 50
  end +
  @@new.inject(" \n\n\nExam is failed by:\n\n") { |out, (k,v)| out + "#{k}, #{v}% (grade F)\n" if v < 50 }
end

然后只需执行此操作即可输出到终端:

puts GradeCalculator.show

这要写入文件:

f.write( GradeCalculator.show )

但是,我可能更倾向于创建成绩与分数的查找,这将大大减少行数show

于 2013-11-06T19:45:23.070 回答