【问题标题】:Ruby OOP - Instance MethodRuby OOP - 实例方法
【发布时间】:2021-12-11 20:05:26
【问题描述】:

Ruby OOP 初学者在这里。尝试构建一个简单的自动售货机代码。

class VendingMachine
  # TODO: add relevant getter/setter to this class to make the scenarios work properly.
  attr_reader :snack_price_cents, :user_balance_cents
  attr_accessor :snack_count

  def initialize(snack_price_cents, snack_count)
    @user_balance_cents = 0
    @snack_count = snack_count
    @snack_price_cents = snack_price_cents
  end

  def insert_coin(input_cents)
    @user_balance_cents = user_balance_cents + input_cents if input_cents
  end

  def buy_snack
    if snack_count.zero? || user_balance_cents.zero?
      @snack_count = snack_count
    else
      @snack_count = snack_count - 1
      @user_balance_cents = user_balance_cents - snack_price_cents
    end
  end
end

我想了解当用户按下按钮购买零食时snack_countuser_balance_centssnack_price_cents 会发生什么?

除了user_balance_cents 之外,似乎一切正常,但我得到了:

should not let you buy a snack if you didn't insert enough money (error path) (FAILED - 1)"

错误。有什么帮助吗?

【问题讨论】:

    标签: ruby oop


    【解决方案1】:

    我猜你的错误是你正在检查 user_balance_cents 不为零,但你没有检查它是否至少为snack_price_cents。

    即如果我投入 10c 并​​尝试购买 50c 的零食,它会给我。

    【讨论】:

    • 谢谢!有用! :)
    猜你喜欢
    • 2015-12-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 2011-08-27
    • 2014-03-06
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    相关资源
    最近更新 更多