Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined method 'each' for Student:Class

I want to load a file, split its content into arrays, and have the class apply to the content.

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

I'm getting

undefined method 'each' for Student:Class (NoMethodError)

on line 28, which is the puts show() line. Any clues on how I can get further on this?

like image 533
johk Avatar asked Oct 18 '12 08:10

johk


1 Answers

I think you have a typo there (among other things). You're doing this:

for i in Student
  puts show()
end

Clearly, the Student class is not a collection which you can iterate. I think, what you meant to write is this:

allStudents.each do |student|
  puts student.show
end
like image 176
Sergio Tulentsev Avatar answered Oct 09 '22 18:10

Sergio Tulentsev