问题描述
可能的重复:
Ruby 块和非括号参数
我不确定我是否理解这个语法错误.我正在使用 Carrierwave 在 Rails 应用程序中管理一些文件上传,但我似乎错误地将块传递给其中一种方法.
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.
以下是 Carrierwave 文档中的示例:
version :thumb do
process :resize_to_fill => [200,200]
end
这是我所拥有的:
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]) }
以上不起作用,我收到语法错误,意外的'}',需要keyword_end
.有趣的是,以下操作完美无缺:
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
那么,我的问题是,为什么我可以使用 do...end
传递一个块,但在这种情况下不能使用大括号?
So, my question is, why can I pass a block using do...end
but not braces in this instance?
谢谢!
推荐答案
试试这个:
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]) }
你有一个优先级问题.{ }
块比 do...end
块绑定得更紧密,比方法调用更紧密;结果是 Ruby 认为您试图提供一个块作为符号的参数,并说不.
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 }
这篇关于Ruby 块语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!