使用实例方法向数组添加元素

Add elements to an array using instance methods

我想向数组中添加元素。每次,元素都通过调用不同的方法作为参数传递。即,调用以下内容:

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

应该return["eggs", "tomato", "tomato", "tomato"].

这是我的完整代码:

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

def items method 中,我对如何在不覆盖之前存在的数组的情况下将项目添加到数组感到困惑。也很困惑我是否需要使用 attr_accessor 来设置和获取传递给 def add_item 的参数,以便我可以在 def items 中使用它们。

  1. 如果添加项目是为了改变收银机的状态,那么它将改变(覆盖)数组。要添加到数组,您可以使用 ruby 的 push 方法,或铲操作符 <<。

    def add_items thing, price, number = 1
      number.times { @log << thing }
            or
      number.times { @log.push thing }
      return @log
    end
    
  2. 除非您希望在 class 之外访问存储数组实例变量,否则不需要 attr_*。