3

def 现在返回方法名称。所以你可以写

private def foo
  p "foo is private"
end

但我有更困难的方法错误:

2.1.1p2 :036 >   private def refresh_prices
2.1.1p2 :037?>       orders = order_items.includes(:book)
2.1.1p2 :038?>       sum = 0
2.1.1p2 :039?>       orders.each do |t|
2.1.1p2 :040 >             t.price = t.book.price
2.1.1p2 :041?>           sum += t.price * t.quantity
2.1.1p2 :042?>           t.save
2.1.1p2 :043?>         end
2.1.1p2 :044?>       self.total_price = sum
2.1.1p2 :045?>       save
2.1.1p2 :046?>     end
SyntaxError: (irb):39: syntax error, unexpected keyword_do_block, expecting keyword_end
    orders.each do |t|
                  ^

没有私有这个 def 返回:refresh_prices。任何人都可以解释为什么它会失败,这是使用私有 def 的坏方法吗?

4

1 回答 1

3

那很有意思。看起来 do/end 块导致语法错误。

如果您使用{}-style 块,它会按预期工作。

private def refresh_prices
          orders = order_items.includes(:book)
          sum = 0
          orders.each { |t|
            t.price = t.book.price
            sum += t.price * t.quantity
            t.save
          }
          self.total_price = sum
          save
        end
# => Object 

我相信它可以被认为是一个错误。我会看看是否有任何关于 Ruby 错误跟踪器的报告。


编辑:我确认这是一个 Ruby 2.1 错误(参见错误 #9308)。它已在当前的 Ruby 版本中修复,因此它将在下一个错误修复版本中可用。

现在,只需使用{}块样式而不是 do/end。

于 2014-01-09T19:40:17.263 回答