当我尝试调用类方法“addStudent”时,我不明白为什么我得到NoMethodError。 我添加了self来从一个实例更改为一个类方法,并且我对我的语法进行了三重检查,以确保我指的是正确的对象。
我对学校对象和方法都进行了简单的放置,它们都指的是School类的相同实例。这是代码。
class School
attr_accessor :name, :location, :instructors, :students
attr_reader :ranking
@@SCHOOLS = []
def initialize(name, location, ranking, students, instructors)
@name = name
@location = location
@ranking = ranking
@students = students
@instructors = instructors
@@SCHOOLS << self
end
def self.setRanking= (ranking)
@ranking = ranking
end
def self.addStudent= (name, grade, semester)
@students << {:name => name, :grade => grade, :semester => semester}
end
def self.removeStudent(name)
@students.delete_if { |student_hash| student_hash[:name] == name }
end
end
school = School.new ("Happy Funtime School",
"NYC",
1,
[ {:name => "Marissa", :grade => "B"},
{:name=>"Billy", :grade => "F"},
{:name => "Frank", :grade => "A"},
{:name => "Sophie", :grade => "C"} ],
[
{:name=>"Blake", :subject=>"being awesome" },
{:name=>"Ashley", :subject=>"being better than blake"},
{:name=>"Jeff", :subject=>"karaoke"}
]
)
school.addStudent("Jesus", "Z", "Y")
错误:
rb:114:in `<main>': undefined method `addStudent' for #<School:0x007fca64099ff8> (NoMethodError)
答案 0 :(得分:2)
您将方法setRanking
,addStudent
,removeStudent
作为类方法,并在其前面加上self.
。但是您使用方法addStudent
作为实例方法。删除self.
以使其成为实例方法。
您正在呼叫addStduent
,但将其定义为addStudent=
(尾随=
)。
def setRanking(ranking)
@ranking = ranking
end
def addStudent(name, grade, semester)
@students << {:name => name, :grade => grade, :semester => semester}
end
def removeStudent(name)
@students.delete_if { |student_hash| student_hash[:name] == name }
end