Why are parenthesis sometimes required in Ruby?

后端 未结 2 1035
庸人自扰
庸人自扰 2021-01-21 04:29

I recently ran into an oddity while looking at some Ruby code from the Rails docs.

Ruby lets you pass arguments like these examples:

redirect_to post_url         


        
2条回答
  •  醉酒成梦
    2021-01-21 04:48

    Curly braces serve double-duty in Ruby. They can delimit a hash, but they can also delimit a block. In this case, I believe your second example is getting parsed as:

    redirect_to do
      action: 'atom' 
    end, alert: "Something serious happened"
    

    Therefore your action: 'atom', which is not valid as an independent expression, gets parsed as such.

    The parentheses serve to disambiguate the {...} as a hash.

提交回复
热议问题