Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does white-space affect ruby function calls?

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?

like image 312
jcuenod Avatar asked Oct 21 '14 07:10

jcuenod


People also ask

Does white space matter in Ruby?

Whitespace might be (mostly) irrelevant to the Ruby interpreter, but its proper use is the key to writing easily readable code.

How do you check whitespace in Ruby?

If you are using Rails, you can simply use: x. blank? This is safe to call when x is nil, and returns true if x is nil or all whitespace.

What is the function of Ruby?

Ruby methods are very similar to functions in any other programming language. Ruby methods are used to bundle one or more repeatable statements into a single unit. Method names should begin with a lowercase letter.


2 Answers

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

like image 179
Dima Avatar answered Sep 23 '22 04:09

Dima


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.

like image 21
Alireza Avatar answered Sep 20 '22 04:09

Alireza