【问题标题】:What's the comma for in this code example?此代码示例中的逗号是什么?
【发布时间】:2009-03-12 19:00:21
【问题描述】:
cash = 100_000.00
sum = 0
cash += 1.00, sum while cash < 1_000_000.00 # underscores ignored

我在“Learning Ruby”一书中找到了上面的例子,但是使用 Ruby 1.9 它不能编译(“解释”?)

syntax error, unexpected ',', expecting $end

1.00 之后逗号应该做什么?

这是示例的完整上下文:

#Also, like if, you can use while as a statement modifier, at the end of a statement:
cash = 100_000.00
sum = 0
cash += 1.00, sum while cash < 1_000_000.00 # underscores ignored
#So cash just keeps adding up until it equals $1,000,000.00. I like that!

【问题讨论】:

    标签: ruby syntax


    【解决方案1】:

    这是一个错误。有一个关于它的 unconfirmed error report,但 official errata 中没有任何内容(自 2007 年 10 月 16 日以来没有更新)。

    【讨论】:

      【解决方案2】:

      它很可能是一个分号,但代码仍然是错误的。我觉得缺少一些上下文。作者用 sum 做什么?

      您可以通过以下方式使用while,这可能有助于解释意图。

      i = 0
      puts i +=1 while i < 10
      

      这意味着这段代码有意义

      cash += 1.00 while cash < 1_000_000.00
      

      【讨论】:

        【解决方案3】:

        好吧,这不是第一本也不是最后一本在代码中有明显拼写错误的编程书籍。

        【讨论】:

          【解决方案4】:

          可能是分号(;)打错或打错了?

          【讨论】:

            【解决方案5】:

            全文如下:

            另外,和 if 一样,您可以在结尾处使用 while 作为语句修饰符 声明:

            cash = 100_000.00
            sum = 0
            
            cash += 1.00, sum while cash < 1_000_000.00 # underscores ignored
            

            所以现金不断增加,直到等于 1,000,000.00 美元。我喜欢!

            这里显然至少有一个错误。我的猜测是作者不小心使用了 perl 或 C 风格的逗号运算符,然后只删除了部分违规语句。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-11-22
              • 2012-02-29
              • 2017-06-19
              • 1970-01-01
              • 2022-01-08
              • 2011-08-05
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多