没有被评估的类方法NoMethodError

时间:2014-07-26 03:02:48

标签: ruby class variables nomethoderror

当我尝试调用类方法“addStudent”时,我不明白为什么我得到NoM​​ethodError。 我添加了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)

1 个答案:

答案 0 :(得分:2)

  1. 您将方法setRankingaddStudentremoveStudent作为类方法,并在其前面加上self.。但是您使用方法addStudent作为实例方法。删除self.以使其成为实例方法。

  2. 您正在呼叫addStduent,但将其定义为addStudent=(尾随=)。


  3. 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