Students & Courses. Accessing course from student

It seems like when I try to run the enroll method, the method is not able to access course.students. My enroll looks like this:

 def enroll(new_course)
    @courses << new_course
    course.students << self
  end

and my entire student class looks like this so far:

class Student
  attr_accessor :first_name, :last_name, :courses, :name, :new_course

  def initialize(first_name, last_name)
    @first_name = first_name
    @last_name = last_name
    @courses = []
  end

  def first_name
    @first_name
  end

  def last_name
    @last_name
  end

  def enroll(new_course)
    @courses << new_course
    course.students << self
  end

  def name
    self.first_name + " " + self.last_name
  end

  def course_load
    courses_and_credits = Hash.new(0)
    @courses.each do |course|
      courses_and_credits[course.department] += course.credits
    end
    courses_and_credits
  end
end

and my course class looks like this so far:

class Course
  attr_accessor :name, :department, :credits, :time_block, :days, :students

  def initialize(course_name, department, credits)
    @name = course_name
    @department = department
    @credits = credits
    @students = []
  end

  def add_student(student)
    student.enroll(self)
  end
end

The error message I get looks like this:

Any time you get a name error like this, it’s usually the result of either a typo or accidentally using a variable that is not defined. This particular error tells you exactly where to look, so it’s super important to always examine the error message. Check the variable course in the enroll method on line 20 of student.rb. :slightly_smiling_face:

My line 20 is course.students << self which I’ve checked many times.
course/students/self all seemed to be spelled correctly and defined.

  def enroll(new_course)
    @courses << new_course
    course.students << self
  end 

This is my full method for the line.

What is course defined as?

Oh, I think I see what I did now. This whole time I thought course.students << self was accessing course class and adding self into students array but it doesn’t work like that. I’m supposed to add the new_course I’ve defined into students. I realize that now :sweat_smile: I’ve changed the method to this:

  def enroll(new_course)
    @courses << new_course
    new_course.students << self
  end

and it passes the specs it wasn’t passing before. Thank you!!!

Can I ask though, how variables/methods in one class can access varibles/methods in the other class so easily? Is it because of attr_accessor?

If you take a look at the top of the spec files, you’ll see code like require 'course'. This is what provides access to methods in the Course class.

By contrast, attr_accessor allows you to access an object’s instance variables within its own class.

1 Like

ohhh I see. Thanks again!