当我使用respond_with
并传递文字哈希时,它给了我错误:
syntax error, unexpected tASSOC, expecting '}'
`respond_with {:status => "Not found"}`
但是,当我将括号中的文字哈希包含在内时:
respond_with({:status => "Not found"})
该功能顺利运行。为什么括号会有所作为?哈希是不是一个封闭的呼叫?
答案 0 :(得分:12)
调用方法时,方法名称后面的左大括号将被解释为块的开头。这优先于作为哈希的解释。解决问题的一种方法是使用括号将解释强制为方法参数。例如,请注意这两个方法调用的含义不同:
# interpreted as a block
[:a, :b, :c].each { |x| puts x }
# interpreted as a hash
{:a => :b}.merge({:c => :d})
另一种方法是摆脱大括号,因为你总是可以跳过方法的最后一个参数的括号。 Ruby非常“聪明”,可以将参数列表末尾看起来像关联列表的所有内容解释为单个哈希。请看一下这个例子:
def foo(a, b)
puts a.inspect
puts b.inspect
end
foo "hello", :this => "is", :a => "hash"
# prints this:
# "hello"
# {:this=>"is", :a=>"hash"}