thinking out loud [...]by @robertodecurnex

Let’s have some fun with some Unicode chars and Heredoc Strings.

Variable Names

Ruby has some pretty relaxed rules over the names of local variables. Basically these names can start with a letter (a-z, A-Z), an underscore (_) or ANY Unicode char not included in ASCII (😁, 😐, 😘, , 7⃣, ). For the following chars you can also include numbers (0-9).

Note: An underscore as the first char will change the way the variable behaves, such like how @, @@ and $ make them instance, class, and global variables respectively, _ will suppress duplicate argument errors. _ by itself will be also overwritten after each sentence with the value of the last eval.

Method Names

Methods naming rules are almost the same. On top of the local variable rules you can add a ? or a ! at the end of the name, commonly used to denote a boolean response or an internal modification of the object instance respectively. Over the time the bang (!) have also been used to distinguish methods that would fail silently form methods that would raise exceptions under the same circumstances.

You can also define/redefine most of the operators (+, -, >, ==) and some other weird unary operators such as -@. It’s a long discussion so we may cover that later.

Note: (From @the_zenspider Ruby QuikRef) “1.9 has a horrible extension to allow you to define !=, !~, !, and not. A special place in hell is reserved for you if you define any of these.”

Heredoc Strings

As many other Ruby features our Heredoc strings are Perl inspired, though they behave much more like the Unix Shell Heredocs sometimes.

The basic usage implies an opening in the form of <<HERE_DOC_ID followed by a new line. Following lines will hold the string itself (new lines included) until a the first line starting with the same HERE_DOC_ID.

Tip: By default the closing HERE_DOC_ID must be at the beginning of the line. This constraint can be ignored, to enable indentation, by adding a - right before the opening HERE_DOC_ID (<<-HERE_DOC_ID).

Now, Ruby let’s you chain things and execute multiple sentences in the same line of the opening HERE_DOC_ID (even using ;). Those operations can include the definition of more Heredocs. Their bodies can then be defined, keeping a left to right order, in the following lines, closing them one at the time. Basically the <<HERE_DOC_ID works as some sort of constant, holding the string defined below.

How about you?

Have you find useful/fun usages for them?

Share them below! I would love to hear your stories.

blog comments powered by Disqus