Can you tell me why this isn't working?
The code below outputs student1 & student2 properly, but I cannot get the class method to work on student3.
All I am trying to do is assign a class method .create_with_species
, with the species attribute = to "Human".
However, when I run the program, I get an error that "local variable or method sex
is undefined". I'm a newbie and I can't figure out what I've done wrong!
It was my understanding that since I had identified "sex" in the Initialize method I should be able to use it within a class method such as create_with_species
. I tried explicitly defining sex in the class method, as student.sex = sex
, but still got the same error.
class Students
attr_accessor :sex, :age, :species
def self.create_with_species(species)
student = Students.new(sex,age)
student.species = species
return student
end
def initialize(sex, age)
@sex = sex
@age = age
puts "----A new student has been added----"
end
end
student1 = Students.new("Male", "21")
puts student1.sex
puts student1.age
puts
student2 = Students.new("Female", "19")
puts student2.sex
puts student2.age
student3 = Students.create_with_species("human")