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
.