Jes Jes - 4 months ago 13
Ruby Question

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?

Answer

The easiest way I think is:

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

But it all comes down to your syntax preferences.

Comments