Search code examples
ruby-on-railsrubysyntax-errorblockcarrierwave

Ruby Block Syntax Error


Possible Duplicate:
Ruby block and unparenthesized arguments

I'm not sure I understand this syntax error. I'm using Carrierwave to manage some file uploads in a Rails app, and I seem to be passing a block to one of the methods incorrectly.

Here's the example in the Carrierwave Docs:

version :thumb do
  process :resize_to_fill => [200,200]
end

Here's what I had:

version :full   { process(:resize_to_limit => [960, 960]) }
version :half   { process(:resize_to_limit => [470, 470]) }
version :third  { process(:resize_to_limit => [306, 306]) }
version :fourth { process(:resize_to_limit => [176, 176]) }

The above doesn't work, I get syntax error, unexpected '}', expecting keyword_end. Interestingly enough, the following works perfectly:

version :full   do process :resize_to_limit => [960, 960]; end
version :half   do process :resize_to_limit => [470, 470]; end
version :third  do process :resize_to_limit => [306, 306]; end
version :fourth do process :resize_to_limit => [176, 176]; end

So, my question is, why can I pass a block using do...end but not braces in this instance?

Thanks!


Solution

  • Try this:

    version(:full)   { process(:resize_to_limit => [960, 960]) }
    version(:half)   { process(:resize_to_limit => [470, 470]) }
    version(:third)  { process(:resize_to_limit => [306, 306]) }
    version(:fourth) { process(:resize_to_limit => [176, 176]) }
    

    You have a precedence problem. The { } block binds tighter than a do...end block and tighter than a method call; the result is that Ruby thinks you're trying to supply a block as an argument to a symbol and says no.

    You can see a clearer (?) or possibly more familar example by comparing the following:

    [1, 2, 3].inject 0  { |x, y| x + y }
    [1, 2, 3].inject(0) { |x, y| x + y }