Ruby Block Syntax Error [duplicate]

浪子不回头ぞ 提交于 2019-11-26 04:28:54

问题


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!


回答1:


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 }


来源:https://stackoverflow.com/questions/6854283/ruby-block-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!