-2

I want to add elements to an array. Each time, elements are passed as parameters by calling a different method. That is, calling the following:

new_register = CashRegister.new
new_register.add_item("eggs", 1.99)
new_register.add_item("tomato", 1.76, 3)

should return ["eggs", "tomato", "tomato", "tomato"].

Here's my code in its entirety:

class CashRegister
  attr_accessor :total, :discount, :title, :price, :array_of_all_items
  def initialize(discount = 0)
    @total = 0
    @discount = discount
  end
  def add_item (title, price, quantity = 1)
    @title = title
    self.total = self.total + (price * quantity)
  end
  def apply_discount
    if
      discount == 0
      "There is no discount to apply."
    else
      total_discount = self.total * (discount / 100.0)
      self.total = self.total - total_discount
      "After the discount, the total comes to $#{self.total.round}."
    end
  end
  def items
    array_of_all_items << self.title
  end
end

Within def items method, I'm stumped on how to add items to the array without overriding the array that was there previously. Also confused about whether I needed to use attr_accessor to set and get the parameters that are passed to def add_item so that I can use them in def items.

Keren
  • 217
  • 1
  • 6
  • 20

1 Answers1

1
  1. If add items is meant to change the state of the cashregister, then it will change(override) the array. To add to an array you can use ruby's push method, or the shovel operator <<.

    def add_items thing, price, number = 1
      number.times { @log << thing }
            or
      number.times { @log.push thing }
      return @log
    end
    
  2. unless you want the storage array instance variable accessible outside of the class, you do not need attr_*'s.

AdamCooper86
  • 3,957
  • 1
  • 13
  • 19