Jes
Jes

Reputation: 343

Ruby, adding multiple objects to an array at once

I have Shop class, and I want to add multiple items at once. I want this:

shop1 = Shop.new
product1 = Product.new("Dress", 50)
shop1.add_products(product1, 5)

to add 5 dresses to warehouse

def add(product, qty)
  @products << product * qty
end

so later I can use

@products.select{|p| p.name == "Dress"}.count

and get 5. Is it possible?

Upvotes: 0

Views: 1814

Answers (3)

BrunoF
BrunoF

Reputation: 3523

Both previous answers will solve your problem. However, maybe you should consider using a hash instead of an array.

Something like this:

 class Product    
  @@products = Hash.new(0)

  def initialize(product, qty)
    @@products[product] = qty
  end

  def increase_stock(product, qty)
    @@products[product] += qty
  end

  def decrease_stock(product, qty)
    @@products[product] -= qty
  end

  def count_stock(product)
    @@products[product]
  end
end

p = Product.new('Dress',5)
p.count_stock('Dress')
 => 5
p.increase_stock('Dress',10)
p.count_stock('Dress')
 => 15
p.decrease_stock('Dress',2)
p.count_stock('Dress')
 => 13

In my GitHub, there is a simple command-line inventory management app written in Ruby. May be useful..

Upvotes: 1

Albin
Albin

Reputation: 3012

The easiest way I think is:

def add(product, qty)
  @products += [product] * qty
end

But it all comes down to your syntax preferences.

Upvotes: 3

Arne Brasseur
Arne Brasseur

Reputation: 1518

You could do something like this

def add(product, qty)
  @products.concat([product] * qty)
end

or less "clever"

def add(product, qty)
  qty.times { @products << product }
end

Upvotes: 3

Related Questions