Dan Zawadzki
Dan Zawadzki

Reputation: 732

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.

Upvotes: 2

Views: 275

Answers (2)

C dot StrifeVII
C dot StrifeVII

Reputation: 1885

You could try this

class Client < Person
  @@clientList = []

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

  attr_reader :wallet, :clientList

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

But to be honest I would suggest that you restructure this code. If you are using are rails this is something the would be much better handled by using active record models with has many associations.

class ClientList < ActiveRecord::Base
  has_many :clients
end

class Person < ActiveRecord::Base
end

class Client < Person
  belongs_to :client_list
end

Upvotes: 0

Andrey Deineko
Andrey Deineko

Reputation: 52357

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>]

Upvotes: 1

Related Questions