Tom*_*ats 3 ruby syntax ruby-on-rails syntax-error ruby-2.2
我最近在查看Rails文档中的一些Ruby代码时遇到了一个奇怪的问题.
Ruby允许您传递像这些示例的参数:
redirect_to post_url(@post), alert: "Watch it, mister!"
redirect_to({ action: 'atom' }, alert: "Something serious happened")
Run Code Online (Sandbox Code Playgroud)
但第二种情况对我来说很奇怪.看起来你应该能够像这样传递它:
redirect_to { action: 'atom' }, alert: "Something serious happened"
Run Code Online (Sandbox Code Playgroud)
无论有没有括号,它都有相同的含义.但相反,你得到:
syntax error, unexpected ':', expecting '}'
Run Code Online (Sandbox Code Playgroud)
参考结肠后action.我不确定它为什么会在}那里期待,为什么使用括号会改变它.
因为{ ... }有两个含义:hash literal和block.
考虑一下:
%w(foo bar baz).select { |x| x[0] == "b" }
# => ["bar", "baz"]
Run Code Online (Sandbox Code Playgroud)
这{ ... }是一个块.
现在假设您正在调用当前对象的方法,因此不需要显式接收器:
select { |x| x[0]] == "b" }
Run Code Online (Sandbox Code Playgroud)
现在假设您不关心参数:
select { true }
Run Code Online (Sandbox Code Playgroud)
在这里,{ true }仍然是一个块,而不是哈希.所以它在你的函数调用中:
redirect_to { action: 'atom' }
Run Code Online (Sandbox Code Playgroud)
是(大部分)相当于
redirect_to do
action: 'atom'
end
Run Code Online (Sandbox Code Playgroud)
这是无稽之谈.然而,
redirect_to({ action: atom' })
Run Code Online (Sandbox Code Playgroud)
有一个参数列表,由一个哈希组成.