【问题标题】:Stuck on LearnStreet Ruby Training. Simple Ruby Code坚持 LearnStreet Ruby 培训。简单的 Ruby 代码
【发布时间】:2012-11-04 23:55:59
【问题描述】:

尝试使用新的 LearnStreet 在线教程学习 Ruby。

试图通过他们的问答系统寻求帮助,但似乎没有人回答。

"你现在可以在 account 对象上实现withdraw! 方法吗? 接受一个参数数量,并将余额减少指定的值 数量?定义方法后,继续提取 100 美元 从帐户中检查余额。”

是问题,我得到了两个提示

" 提示 1 代码 @balance = @balance - amount 减少金额 @平衡。

提示2 然后调用方法withdraw!在帐户对象上 - account.withdraw!(100)。 "

我的尝试是

def

account.widthdraw!

@balance = @balance - amount

end

account.withdraw!(100)

任何想法我缺少什么?

【问题讨论】:

    标签: ruby


    【解决方案1】:

    “你现在可以在account对象上实现withdraw!方法,它接受一个参数amount,然后将余额减少指定的金额吗?定义方法后,继续从账户中提取100美元并检查余额。”

    一步一步:

    • “你现在可以在帐户对象上实现withdraw!方法吗

      class Account
        def withdraw!
        end
      end
      
    • 采用一个参数量...

      class Account
        def withdraw!(amount)
        end
      end
      
    • 并将余额减少指定的金额?

      class Account
        def withdraw!(amount)
          @balance = @balance - amount
        end
      end
      
    • 定义方法后,继续从账户中提取100美元并检查余额。”

      account = Account.new
      account.withdraw!(100)
      

    【讨论】:

      【解决方案2】:

      我想你会想要这样的东西。

      class Account
      
          def withdraw! amount
               @balance -= amount
          end
      
      end
      

      【讨论】:

      • 为了澄清@user1739696,@balance = @balance - amount 在大多数情况下等同于@balance -= amount。通过def account.withdraw! 定义将在特定情况下工作,但它并不适合这种情况。此外,您似乎在这里错过的一件大事是amount 参数。 (对不起@alex,没有试图超越你的答案)
      • @JimDeville 感谢您的澄清,谢谢。我不是 Ruby 专家,因此很重视您的反馈。
      【解决方案3】:

      这是这个问题的答案:

      def account.withdraw!(amount)
          @balance = @balance - amount
      end
      account.withdraw!(100)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-10
        • 2013-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多