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)
Student的未定义方法'each':Class(NoMethodError)
on line 28, which is the puts show()
line. Any clues on how I can get further on this?
在第28行,这是puts show()行。有关如何进一步了解这一点的任何线索?
2 个解决方案
#1
3
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:
显然,Student类不是可以迭代的集合。我想,你打算写的是:
allStudents.each do |student|
puts student.show
end
#2
2
That is because you are trying to iterate over "Student" class and not Array/Collection object at for i in Student
那是因为你试图在Student中迭代“Student”类而不是for i的Array / Collection对象
Basically you are doing it wrong. It rather should be something like
基本上你做错了。它应该是类似的东西
allStudents.each do |student|
puts student.show
end
#1
3
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:
显然,Student类不是可以迭代的集合。我想,你打算写的是:
allStudents.each do |student|
puts student.show
end
#2
2
That is because you are trying to iterate over "Student" class and not Array/Collection object at for i in Student
那是因为你试图在Student中迭代“Student”类而不是for i的Array / Collection对象
Basically you are doing it wrong. It rather should be something like
基本上你做错了。它应该是类似的东西
allStudents.each do |student|
puts student.show
end