Dan Zawadzki Dan Zawadzki - 1 month ago 8
Ruby Question

RoR Adding object to an array already in def initialize?

This is my first attempt with Ruby on Rails, so I apologize if the question is obvious, but unfortunately I can not find the answer anywhere.

class Client < Person

clientList = []

def initialize(name, surname, email, wallet)
super(name, surname, email)
@wallet = wallet
end

attr_reader :wallet, :clientList

def to_s
super + ", #{@wallet}"
end

def add_to_array
clientList + this.object
#i know its not correct
end
end


I would like to create method, which allow me to add instances of client class to clientList array. What else is there later any option to use this method already in
def initialize(name, surname, email, wallet)
. Something like
this.add_to_array


I would like to have array with all clients inside, but i don't want to use method add_to_array everytime i create new client. It should be automatic.

Answer

To add client instances to clientList you have to change clientList to be at least class instance variable, add accessor for it and a call add_to_array (I'd rename it to add_to_clients_list) to initialize method, so that the clientList updates everytime the Client instance is created:

class Client < Person

  @clientList = []

  class << self
    attr_accessor :clientList # add an accessor, so you can use Client.clientList
  end

  def initialize(name, surname, email, wallet)
    super(name, surname, email)
    @wallet = wallet
    add_to_array # call a method, that adds this created instance to array
  end

  attr_reader :wallet, :clientList

  def to_s
    super  + ", #{@wallet}"
  end

  def add_to_array
    self.class.clientList << self 
  end
end

Now:

# create instance of Client
Client.new(1,2,3,4)
#<Client:0x007f873db25a68 @wallet=4>
# It is automatically added to `clientList`
Client.clientList
#=> [#<Client:0x007f873db25a68 @wallet=4>]