Why does white spaces affect ruby ​​function calls?
I am getting 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")
}
Why is this space after render_to_string
breaking my rails app?
source to share
The point is that this 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 arguments after a space. and you can run Array.new(1,2)
as well, and ruby ​​knows the arguments are in parentheses.
but when run Array.new (1,2)
ruby thinks it will get arguments after the space, but it actually gets a tuple (1,2)
, and basically it is exactly the same asArray.new((1,2))
so the bottom line is:
Array.new (1,2)
== Array.new((1,2))
and this is a syntax error because (1, 2)
literal is not valid
source to share
As a general guide to Ruby style, you shouldn't put a space before parameter brackets. it is not rails related, but Ruby language. try this:
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 expected to find )
, but found ,
. However, in the last example, it didn't break.
source to share