2012-10-18 19 views
5

我想加载一个文件,将它的内容分割成数组,然后让这个类适用于内容。线路28上,这是puts show()线类(NoMethodError)未定义的方法'each'给Student:Class

class Student 
    def initialize(name, grade) 
     @name = name 
     @grade = grade 
     @grade = @grade.to_i 
     @newgrade = @grade*1.45 
    end 

    def show() 
     return "#{@name} ,#{@grade} , #{@newgrade}" 
    end 
end 

# Opening the file into an array 
arr = File.open("exam_results.txt", "r+") 
allStudents = Array.new 

for a in arr 
    b = a.split(",") 
    name = b[0] 
    score = b[1] 
    allStudents << Student.new(@name, @grade) 
end 

for i in Student 
    puts show() 
end 

我得到

未定义的方法 '各自' 的学生。任何关于如何进一步研究的线索?

回答

3

我认为你有一个错字(除其他外)。你这样做:

for i in Student 
    puts show() 
end 

显然,Student类不是,你可以遍历集合。我想,你的意思写的是:

allStudents.each do |student| 
    puts student.show 
end 
+0

工作!感谢您的帮助! :) – johk

2

那是因为你正试图遍历“学生”类,而不是数组/集合对象在for i in Student

基本上你是做错了。它应该是像

allStudents.each do |student| 
    puts student.show 
end 
+1

我是第一个,mwahaha :) –

+0

+1对^评论:)你让我笑了。 – ch4nd4n

+0

工程奇迹,非常感谢! :) – johk