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")
sexandageare not defined. Do you mean to use a class variable? Using@ageor@sexwill result in nils, as no class attributes are set and the instance is not yet created, hence no instance variables set either. You don’t need to stateStudents.newincreate_with_species.newwill suffice because you are scoped inStudents. I think you would be better off passing a hash object to initialize, and just set the species variable there. It will be nil if not assigned explicitly, or you can have a default value.Try this: