Ruby Syntactical Sugar Pitfalls

Ruby hides away under the hood a lot of writting which are common in other languages. One benefit is easier and faster writting, and (generally) easier parsing of the code.

There are some pitfalls to this syntactical sugar.

Local Variable and Method with the Same Name

Say we have a code with a variable and a method of the same name:

stringify = 'a string'

def stringify
  'a method'

p stringify # => "a string"

It seems that when a method and a variable have the same name, Ruby prioritizes the variable over the method invocation. This is actually not the case.

What happen is we asked Ruby to print the variable stringify. If we wanted to invoke the method, we would need to use:

p stringify() # => "a method"

Like a lot of other programming language, Ruby uses the syntax method_name + () to invoke a method. This syntax can be shortcut to method_name if and only if there is no method with the same name.

Most of the time though, our code will use the shortcut writting. It’s best to avoid this problem altogether and use different names for our methods and our variables.

Using Too Much Syntax Shortcut

Taking the same example as above, what we are actually trying to do is:

p(stringify()) # => "a method"

While p stringify is easier to read (closer to English), it does not tell you if stringify is a method or a variable.

Counsciously writting parenthesis aroud method, like p(stringify), while slightly more difficult to parse, is more straightforward: we are using the method p() on a variable stringify.

Syntax Error

With ternary operator we cannot take advantage of Ruby’s syntactical sugar:

boolean = [true, false].sample
boolean ? puts "I'm true!" : puts "I'm false!"

The code aboce would result in a SyntaxError:

syntax error, unexpected string literal, expecting `do' or '{' or '(')

The error tells use we have to add parentheses around the argument:

boolean ? puts("I'm true!") : puts("I'm false!")