Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Class method that returns an instance & modifies that instance

Tags:

ruby

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?

like image 952
Alex Marchant Avatar asked Aug 26 '26 14:08

Alex Marchant


2 Answers

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
like image 60
xdazz Avatar answered Aug 28 '26 03:08

xdazz


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.

like image 38
Dan Tao Avatar answered Aug 28 '26 05:08

Dan Tao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!