Why is space in this ruby ​​challenge so important?

I am writing a jsonify view in a Rails application. I have:

json.samba_secrets_present(not @idp_ad_info.samba_secrets.nil?) 

This creates a syntax error:

 app/views/idp_ad_infos/show.jsonify:7: syntax error, unexpected tIVAR, expecting '(' 

However

 json.samba_secrets_present (not @idp_ad_info.samba_secrets.nil?) 

works great. I would suggest that the first would be a method call for the samba_secrets_present method of a Jsonify::Builder object with the first argument not idp_ad_info.samba_secrets.nil? . Why is space significant?

+5
source share
1 answer
 puts(not true) #=> error puts (not true) #=> false, CASE 2 puts(not(true)) #=> false 

Ruby allows you to omit the bracket to sometimes call a method. Generally, if there is only one method call, you can omit the parentheses. However, you cannot omit this when the method call is in the argument position of another method call (general case, see the special case in the Update section), because this will lead to ambiguity. Consider the following example:

 puts(not true, false) puts(some_method arg1, arg2) 

The Ruby analyzer cannot determine if false (or arg2 ) is an argument of an internal method or an external puts , so it raises an error for this case. The parser does not have a runtime context to determine the arity of the internal method, so it does not matter if it is a unary method (for example, not ) or not.

Take CASE 2 as an example, which is interpreted as:

 puts( (not false)) 

And you can write:

 puts (not false), true, (not true) 

all arguments for puts .

Some links: Positional Arguments

Update: toro2k commented that puts(system 'ls') works. This is because system accepts *args , which will capture all other arguments. There will be no arguments for an external method, definitely :). As a result, in this case there is no ambiguity.

 def a *args args end p(a 1, 2, 3, 4) #=> [1, 2, 3, 4] 

However, I would vote to write clearer code with the necessary brackets to make the code more readable.

+5
source

All Articles