Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

264
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!