seaoftime
seaoftime

Reputation: 21

How do I work with specific class instances in Ruby?

I want to make a small application where users can create a list of stores and inventories for the stores. Here's what I have for the store class:

class Store
  attr_accessor :name, :inventory
  
  def initialize(name)
    @name = name
    @inventory = []
    @@all << self
  end

end

It initializes with an empty array, and I want to fill it up with items (as strings). I'm aware you can use, say newStore = Store.new to create a store and then further call on newStore, but I want the user to be able to create as many stores as they want and when they create a second newStore it will override that variable. How do I re-access that previous class instance to edit the inventory array?

Upvotes: 1

Views: 40

Answers (1)

spickermann
spickermann

Reputation: 106882

You can change it to the following and just create a new array when it wasn't initialized before:

def initialize(name)
  @name = name
  @inventory = []
  @@all ||= []
  @@all << self
end

Upvotes: 2

Related Questions