I am trying to store a collection of objects within another object. I completed a coding challenge that looks like the following.
First the singular object:
class Account
attr_reader :user_name, :credit, :debit
def initialize(user_name)
@user_name = user_name
@credit = 0
@debit = 0
end
end
Next the collection:
class AccountsCollection
attr_reader :accounts
def initialize
@accounts = []
end
def add_new_account(user)
accounts << Account.new(user)
end
...
end
This is how I use it:
accounts = AccountsCollection.new
# => #<AccountsCollection:0x00007fc76ba70b18 @accounts=[]>
accounts.add_new_account('A')
accounts.add_new_account('B')
accounts.add_new_account('C')
accounts.accounts
# =>[
# #<Account:0x00007fc76b933890 @user_name="A">,
# #<Account:0x00007fc76bc76d68 @user_name="B">,
# #<Account:0x00007fc76c88c2d8 @user_name="C">
# ]
I wanted to use it like this:
class Display
attr_reader :accounts
def initialize(accounts)
@accounts = accounts
end
def display_inline
accounts.each do |account|
#do something
end
...
end
Display.new(accounts.accounts).display_inline
But I have to call accounts.accounts to obtain the list of account objects. Is this weird? Can anyone show me how I can do this better?
AccountsCollection. Why do you need / want to have direct access to it?AccountsCollection, just rename theaccountsmethod toto_a.