题
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吗?
解决方案
这很有意思。它看起来像DO / END块导致语法错误。
如果使用{}
块,它可以按预期工作。
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 Bug跟踪器上有任何报告。
编辑:我确认它是一个Ruby 2.1错误(请参阅 bug#9308 )。它已在当前的Ruby版本中修复,因此它将在下一个Bugfix版本中提供。
现在,只需使用{}
块样式而不是DO / END。 不隶属于 StackOverflow