Looking to set up a class method that can return an array of instances. I'm running into some trouble about the point where I try to modify the instances' variables NoMethodError: undefined method 'name=' for #<Class:0x007fe65c8560c0>.
class User
attr_accessor :name
def self.sample_users
megan = self.class.new
megan.name = "Megan"
jack = self.class.new
jack.name = "Jack"
[megan, jack]
end
end
I feel like this should be possible in Ruby. Any guidance?
Use just new instead of self.class.new
class User
attr_accessor :name
def self.sample_users
megan = new
megan.name = "Megan"
jack = new
jack.name = "Jack"
[megan, jack]
end
end
The value of self in this context is User (sample_users is a class method); so self.class is going to return Class.
I think you just want self.new.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With