Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store a collection of Ruby objects

Tags:

oop

ruby

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?

like image 912
Keith Chong Avatar asked Feb 24 '26 13:02

Keith Chong


1 Answers

Really it looks good to me other than the naming looking awkward. If it was me, I'd have the names like this so it looks good using it.

class AccountsCollection
  def initialize
    @accounts = []
  end

  def add(user)
    accounts << Account.new(user)
  end

  def to_a
    @accounts
  end
end

Then your code would look like

accounts = AccountsCollection.new
 => #<AccountsCollection:0x00007fc76ba70b18 @accounts=[]>

accounts.add('A')
accounts.add('B')
accounts.add('C')

accounts.to_a
 =>[
   #<Account:0x00007fc76b933890 @user_name="A">,
   #<Account:0x00007fc76bc76d68 @user_name="B">,
   #<Account:0x00007fc76c88c2d8 @user_name="C">
 ]
like image 79
iCodeSometime Avatar answered Feb 27 '26 02:02

iCodeSometime



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!