9

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!

Community
  • 1
  • 1
Andrew
  • 42,517
  • 51
  • 181
  • 281
  • This is a duplicate of [Code block passed to `each` works with brackets but not with `do`-`end` (ruby)](http://StackOverflow.Com/q/6718340/), [Block definition - difference between braces and `do`-`end` ?](http://StackOverflow.Com/q/6179442/), [Ruby multiline block without `do` `end`](http://StackOverflow.Com/q/3680097/), [Using `do` block vs brackets `{}`](http://StackOverflow.Com/q/2122380/), [What is the difference or value of these block coding styles in Ruby?](http://StackOverflow.Com/q/533008/) and [Ruby block and unparenthesized arguments](http://StackOverflow.Com/q/420147/). – Jörg W Mittag Jul 28 '11 at 08:16

1 Answers1

16

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 }
mu is too short
  • 426,620
  • 70
  • 833
  • 800