Sweet Sweet Syntax — in Ruby

Pascal Rassaby (Pas byNumbers)
10 min readMay 29, 2019

This post assumes you have knowledge of:

  • Variables and data types
  • Iteration and Enumerables
  • Methods
  • Arrays

Programming is Art?

When I first started learning programming. I thought it was all logical statements and strict ‘computer speak’. I used to think that there was no room for any personalisation or signature style other than abiding by the original idea you conceptualised when creating a project.

Being one of many programmers who came from a musical background, I’m sure I am not alone in saying that programming doesn’t feel like an art-form nor does it have any room for art. If you want to be artistic whilst retaining technicalities, then you’re better off going in to digital design or UI/UX… well at least that was the tune I used to hum along to.

Spending the past couple weeks learning Ruby has taught me to think very different and that i’ve been somewhat harsh in my opinion towards programming and it’s sense of artistry. Yukihiro Matsumoto or ‘Matz’ for short, created Ruby to be a language that programmers love to use, encouraging a simplistic and elegant style. A program that adds some art to the formula.

Thank you Matz 🙃

I won’t lie, I didn’t see this at first. Despite knowing the language creator’s intentions, I really couldn’t see it. But I suppose that’s how it is when you first learn to program, the ‘personality’ of the language is wasted on you while your focus is on learning the logic and how the language functions as whole to make the bigger picture. This feeling didnt last long though, after reaching a certain level of comfort with Ruby, it really started to occur to me that there was something about this language that was almost ‘inviting’.

Matz wasn’t kidding…

Ruby introduced me to programming as an art form, and you can see for yourself.

The keywords, syntax and general semantics of the program are almost ‘human speak’, so much that it’s easy to see what the code is doing, even with little programming experience, it doesn’t take much to figure out. What’s funny is that the idea behind Ruby sparked off a strong following that literally rave about the language like it’s the best thing ever made since the invention of the motherboard, yet this avid community of programmers are brought together by similar ideals and concepts.

That ideal being that…

PROGRAMMING CAN BE ARTISTIC!!

All these Rubyists follow certain conventions and methodologies that make up their ‘coding style.’ A coding style inspired by Ruby.

Which brings me to my first topic that I want to share whilst I journey in to the world of programming.

The Idea behind sweet syntax

Other than adhering to the elegant format of Ruby’s syntax in comparison to say… Javascript (sorry mate!), I also learnt how to generally condense my code in to a more concise structure.

Hold on, hold on… let’s just have one more dig at Javascript

Others would refer to this as syntactic sugar, I’m just going to call it…

Sweet Syntax

This means to write your code in such a way that is efficient to the programmer whilst also effective to the program itself. The general conventions to code in a ‘sweet style’ are as follows:

(This applies to other programming languages as well!)

  • Code ‘DRY’ not ‘WET’

DRY stands for ‘Don’t Repeat Yourself’, while WET is obviously the complete opposite, which is ‘Write Everything Twice’. It means that you should program in a way that your code doesn’t appear repetitive. This makes it easy to pinpoint what your code is doing, as opposed to seeing similarities in different sections of your code, which can come across as confusing. This convention ties in nicely with the S.R.P concept which we will touch on soon.

  • If you can achieve the same result with less lines of code, DO IT!

Why would you want to write more than you need to, I understand that extra lines of code provide more detail than a more concise format but regardless, it wouldn’t be hard to figure out what’s happening in the code if the effects are still the same. This is one of those ‘easy on the eyes’ type philosophies that just makes your code in general more approachable. Trust me, your future self would thank you!

  • Name your variables and methods/functions appropriately

I mean this goes without saying, honestly… how are you able to follow what your code is doing if you have no idea what your code is referring to. If your were making a variable assigned to a user’s email address, then it would be meaningful to name it something like, I dunno, user_email maybe? This really saves you in the long run when you have 100s or even 1000s of lines of code to look through, little things like these keep the stress away, believe me.

  • S.R.P

This is based off the idea of DRY code. S.R.P stands for ‘Single Responsibility Principle’ which inspires the concept that each factor of code to stick to one process, one role, one responsibility. You can see this methodology in practice when you look at a ‘run’ file, of which has the sole responsibility of executing other methods, nothing more, nothing less.

Doing this helps when it comes to testing and debugging as any broken code can easily be found due to an S.R.P structure helping to isolate the code

  • Keep your coding style consistent

When you’re first learning to code, it can be easy to be inconsistent in your style of coding as we are constantly learning new things at 300mph. We are constantly applying new concepts in to our code so often that structuring our code becomes one of the last things we consider during our early days as a programmer.

Again, do the following and your future self would thank you..

If you indent all your hashes identically, you can easily see what is a hash and what isn’t just at a glance. You wouldn’t even need to look for a key:value pair.

If you write all your methods in a set way, you can spot where there are loops, conditionals and iterators without needing to spend more than a second looking at the code. It’s simple, if you’re gonna program in a certain style, stick to that style at least for the rest of the project.

Bonus:

  • Use the ‘notes/comments’ feature

Every language has a notes feature, even domain-specific languages have a way to input lines of code that’s sole responsibility is to provide context to whoever is analysing the code. It’s so useful, especially if you’re the type of person who likes to write ideas down. This method of note-keeping makes your journey through programming a much smoother ride now you can keep track of what you’re learning and doing.

Now for some Ruby specifics

I’ve been hammering ideas of concision and productivity in to your style of coding but not yet mentioned how to apply those to Ruby

Below are some examples of condensing your syntax for an ‘easier to read and easier to type’ approach for programming with Ruby

Condensing your code blocks

I’ll keep this one relative simple because it’s a simple process.

Whenever you have a code body which is to say, a block of code that is processed through a method, a loop or any command you issue through your program that requires extra lines of code to be executed along with it, you can create that same code body with a neater structure.

You could write the following to loop a string 5 times:

Or you could just do this:

Do you see.. It’s so much easier on the programmer, and it’s still easier to understand what’s going on.

Let’s go through another example with a little more explanation this time. I have an array [1, 2, 3] and I want to iterate though each index and output that index to the console

So this would be the standard way of coding that process. Now for something more artistic, oh and with a little explanation on top

As you can see, we omit the do and end keywords that initiate a code body and instead use curly braces. The placeholder has the same role with curly braces as it did without, it still houses an argument. Then you input your code body after the place holder and close the statement.

There you have it! Less code, same effect!

Re-tune your strings

This style of writing strings is new to me as well, I’ve yet to start coding like this but I do see the benefits in doing so.

We’re used to writing strings like so:

puts "Do you even code bro?"

But what if we could tell ruby to expect a string without quotes

%(Do you even code bro?)
%{Do you even code bro?}
%|Do you even code bro?|
# These would also work

The % operator allows us to input strings without declaring quotes and yet still works with methods like string interpolation. You wouldn’t have to use escape characters on your quotes either because using quotes in this manner wouldn’t close your string statement.

Now what if we could make an array of strings without needing quotes and commas to separate the indexes.

This is a standard way of writing an array of strings

people = [
"Anne",
"Elizabeth",
"Erica",
"Iryna",
"Johanna",
"Juliane",
"Katja",
"Katrin",
"Maria",
"Renate",
"Sureka",
"Miriam",
"Zazie",
"Anja"
]

Now if we were to re-write this array without so much need for punctuation

people = %w(
Anne
Elizabeth
Erica
Iryna
Johanna
Juliane
Katja
Katrin
Maria
Renate
Sureka
Miriam
Zazie
Anja
)

How does this work? How does Ruby know each word is its own index per se

Well by using the %w operator, Ruby knows to group each element it picks up as a word, a singular string element to be assigned it’s own index. Much easier right?

Just remember that %w only works for strings so using numerics instead won’t yield the same results

Ok, ok, last one and I’ll let you go…

&: and &method

I find this one quite hard to breakdown and i’m still green behind the ears when it comes to programming so explaining the benefits of this approach is beyond me at this level. Still I will show you the technique and implore you to do some further reading on it before attempting it within your own code.

Writing methods tend to go something like this:

# I won't condense the code block here for the sake of better understanding what is happening

def capitalize(array)
array.map do |i|
i.upcase
end
end

If you were to pass an array of strings through this method’s argument, it would return a new array with every letter capitalised. It does this by applying the processes in the method to each index one at a time.

This method can be condensed like so:

def capitalize(array)
array.map(&:upcase)
end

Easy to understand right.

The map method is called on the array and for each index that Ruby maps through, the upcase method is applied to it due to the &:

Again this saves you from needing to include do and end but it also omits the need for placeholders too.

Now what if I was to do this:

def capitalize(array)
array.map(&method(:upcase)
end

This seems less condensed now but would you be surprised that the results you receive from using this technique tend to be more accurate. Why?

Well Ruby reads the element that follows &as a proc, which is an object that serves as a block of code bound to a set of local variables. It is an element of code that is more easily interpretable by Ruby because it holds the local variables as parameters within it’s own object properties

So in the code above, each index of the array is either being read as a proc or Ruby will convert it in to one, then the upcase method is called on each proc.

Again, I recommend further reading on this technique as well as any new programming concepts you come across. Make sure you have full understanding of what your code is meant to do before implementing it.

Other than that, I hope i’ve imparted some useful knowledge for you to take away and maybe inspired some style that brings a more artistic nature to your code.

Thank you for enjoying my post and check back soon for more content!

Oh and before you go…

Here’s one more cheeky programming meme for fun.

References and further reading:

Some examples and images have been sampled from the following sources

https://www.slideshare.net/SkyWang5/ror-vsnodejsbyjcskyting-60614456

https://www.brianstorti.com/understanding-ruby-idiom-map-with-symbol/

https://andrewjgrimm.wordpress.com/2011/10/03/in-ruby-method-passes-you/

http://ruby-for-beginners.rubymonstas.org/blocks/syntax.html

http://ruby-for-beginners.rubymonstas.org/bonus/alternative-syntax.html

https://www.rubyguides.com/2016/02/ruby-procs-and-lambdas/

--

--

Pascal Rassaby (Pas byNumbers)

Building creative and intuitive code that hopefully doesn’t destroy anything :]