Why does white-space affect ruby function calls?

2019-01-20 13:57发布

I get a syntax error with this code

render json: {
    "what" => "created", 
    "whatCreated" => "thing",
    "htmlOutput" => render_to_string (partial: "some_partial")
}

But with this code I don't:

render json: {
    "what" => "created", 
    "whatCreated" => "thing",
    "htmlOutput" => render_to_string(partial: "some_partial")
}

How come that space after render_to_string breaks my rails app?

2条回答
beautiful°
2楼-- · 2019-01-20 14:13

As a general Ruby style guide you should not put a space before the parameter list parentheses. this is not related to rails, but the Ruby language. try the followings to see:

Array.new(1,2) # => [2]
Array.new (1,2) # = > SyntaxError: unexpected ',', expecting ')'
Array.new(1) # => [nil]
Array.new (1) # => [nil]

As you can see in the second example the code broke, the interpreter was expecting to find a ) but found ,. However in the last example it didn't break.

查看更多
别忘想泡老子
3楼-- · 2019-01-20 14:15

the thing is, that method in ruby can be run with or without parentheses. for example, you can run Array.new 1,2 and ruby knows that it receives the arguments after the space. and you can also run Array.new(1,2) and ruby knows the args are inside the parentheses.

but, when you run Array.new (1,2) , ruby thinks it will receive arguments after the space but actually it receives a tuple (1,2), and basicaly its exactly the same as Array.new((1,2))

so bottom line:

Array.new (1,2) == Array.new((1,2)) and thats a syntax error because (1, 2) literal is not a valid one

查看更多
登录 后发表回答