2012-10-18 18 views
5

Desidero caricare un file, dividere il suo contenuto in array e fare in modo che la classe si applichi al contenuto.Metodo non definito 'ciascuno' per Studente: Classe

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 

mi sto

metodo non definito 'ogni' per studente: Classe (NoMethodError)

sulla linea 28, che è la linea puts show(). Qualche idea su come posso andare oltre?

risposta

3

Penso che tu abbia un errore di battitura lì (tra le altre cose). Stai facendo questo:

for i in Student 
    puts show() 
end 

Chiaramente, la classe Student non è una collezione che è possibile scorrere. Credo che, ciò che si intende scrivere è questo:

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

funziona! Grazie per l'aiuto! :) – johk

2

Questo è dovuto al fatto che si sta tentando di iterare classe "Student" e non Array/oggetto Collection in for i in Student

In sostanza si sta facendo male. Piuttosto dovrebbe essere qualcosa come

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

Sono stato il primo, mwahaha :) –

+0

+1 per^commento :) mi hai fatto ridere. – ch4nd4n

+0

Funziona meraviglie, grazie mille !! :) – johk

Problemi correlati