Question

def now returns method name. So you can write

private def foo
  p "foo is private"
end

but I had error with more difficult method:

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|
                  ^

without private this def returns :refresh_prices. Can anyone explain why it fails and is it a bad way to use private def?

Was it helpful?

Solution

That's interesting. It looks like the do/end block is causing a syntax error.

If you use the {}-style block, it works as expected.

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 

I believe it could be considered a bug. I'll see if there is any report on the Ruby bug tracker.


EDIT: I confirm it's a Ruby 2.1 bug (see bug #9308). It has been fixed in the current Ruby version, thus it will be available in the next bugfix release.

For now, simply use the {} block style instead of do/end.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top