Ruby文件输出完全一样

时间:2013-11-06 19:33:44

标签: ruby text output

我在这里遇到一个小问题!

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

1 个答案:

答案 0 :(得分: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中的行数。