0

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?

1
  • Be careful, though: when you do [item] * 3, you get an array of three references to the same item, not three items. Altering any of them will affect all the array items. Commented Jul 6, 2016 at 13:49

3 Answers 3

3

The easiest way I think is:

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

But it all comes down to your syntax preferences.

Sign up to request clarification or add additional context in comments.

1 Comment

The difference with the concat version is that this one creates a new array, instead of adding to the existing one. They're both valid ways to do it. I did an in-place edit because that's what the OP did as well.
3

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

Comments

1

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..

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.