8

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?

jcuenod
  • 55,835
  • 14
  • 65
  • 102

2 Answers2

17

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

Dima
  • 8,586
  • 4
  • 28
  • 57
  • ok, you use my example to explain the underlying issue, but why mark down my answer ? – Alireza Oct 21 '14 at 12:18
  • Surely ruby could be smarter and not assume a tuple unless that's the expected parameter (arrays are a slightly different question but `render_to_string`? (actually I don't know what `render_to_string` accepts but there are plenty of methods that accept specific parameters) – jcuenod Oct 21 '14 at 12:26
  • its not different, its exactly the same, both are methods – Dima Oct 21 '14 at 12:27
  • Yes but arrays could be filled with variable the imaginary method `integer_to_string` could only take an integer – jcuenod Oct 22 '14 at 09:42
6

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.

Alireza
  • 2,641
  • 17
  • 18