Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 为什么在Ruby中有时需要括号?_Ruby On Rails_Ruby_Syntax_Syntax Error_Ruby 2.2 - Fatal编程技术网

Ruby on rails 为什么在Ruby中有时需要括号?

Ruby on rails 为什么在Ruby中有时需要括号?,ruby-on-rails,ruby,syntax,syntax-error,ruby-2.2,Ruby On Rails,Ruby,Syntax,Syntax Error,Ruby 2.2,最近,我在查看来自Web的一些Ruby代码时遇到了一个奇怪的问题 Ruby允许您传递如下示例所示的参数: redirect_to post_url(@post), alert: "Watch it, mister!" redirect_to({ action: 'atom' }, alert: "Something serious happened") 但第二个案例在我看来很奇怪。看起来你应该可以这样通过考试: redirect_to { action: 'atom' }, alert: "S

最近,我在查看来自Web的一些Ruby代码时遇到了一个奇怪的问题

Ruby允许您传递如下示例所示的参数:

redirect_to post_url(@post), alert: "Watch it, mister!"
redirect_to({ action: 'atom' }, alert: "Something serious happened")
但第二个案例在我看来很奇怪。看起来你应该可以这样通过考试:

redirect_to { action: 'atom' }, alert: "Something serious happened"
不管有没有括号,它都有相同的意思。但是你得到的是:

syntax error, unexpected ':', expecting '}'

指动作后的冒号。我不知道为什么它会在那里期待
}
,为什么使用括号会改变这一点。

花括号在Ruby中起双重作用。它们可以分隔散列,但也可以分隔块。在本例中,我相信您的第二个示例被解析为:

redirect_to do
  action: 'atom' 
end, alert: "Something serious happened"
因此,您的
操作:'atom'
,作为独立表达式无效,因此会被解析为独立表达式


括号用于消除将
{…}
作为散列的歧义。

因为
{…}
有两种含义:散列文字和块

考虑这一点:

%w(foo bar baz).select { |x| x[0] == "b" }
# => ["bar", "baz"]
这里,
{…}
是一个块

现在假设您正在对当前对象调用一个方法,因此不需要显式接收器:

select { |x| x[0]] == "b" }
现在假设您不关心参数:

select { true }
这里,
{true}
仍然是一个块,而不是散列。在函数调用中也是如此:

redirect_to { action: 'atom' }
(大部分)相当于

redirect_to do
  action: 'atom'
end
这是胡说八道。但是,

redirect_to({ action: atom' })

有一个由散列组成的参数列表。

嘿,否决票是怎么回事?这个答案是正确的。