How to Write Ruby Like a Pro — A Brief Style Guide

So you’ve been writing Ruby for a while. Maybe you’re familiar with control flow, data types, and the overall way to work with Ruby.

Before you start writing large programs or before working with others, it’s important that your code is consistent and sticks to a single style.

In this article, I’m going to give you some guidance on how to write Ruby that looks nice and that will be similar to how others write Ruby.

I got these guidelines while reading Eloquent Ruby by Russ Olsen. In his book, so if you want to know more about writing readable Ruby code, make sure to pick up his book.

Use spaces, not tabs

Make sure your code editor is set up to use spaces instead of tabs. And make sure that you are using two tabs for each level of indention.

Use # for comments

The hash sign (#) is used for comments in ruby. It’s also possible to write multi-line comments like so:

But in the real world, most Rubyists use # even for multi-line comments.

Use snake_case for pretty much everything

Methods and variables should use snake_case. Constants should use SCREAMING_SNAKE_CASE.

Use parentheses most of the time

In Ruby, parentheses are optional. Here are two ways to call the same method in Ruby:

You should usually use parentheses when calling methods. However, some methods are often called without parentheses such as:

It’s very common to not use parentheses in Ruby on Rails.

You can also use parentheses in conditionals like so:

Instead, you should omit the parentheses:

It’s possible to write code-blocks in one line. Instead of this,

Use single-line code blocks when possible

Here’s a normal code block

you can write it as a single-line code-block:

Make use of if, unless, while, and until

In Ruby, you can write a conditional like so:

But you can also write a single-line conditional like so:

You can also take advantage of unless:

While and until can also be used similarly:

The best way to learn how to write readable Ruby code is to read Ruby code written by more experienced developers. So, make sure you’re reading code by others often.

If you found this post helpful and want to get better at Ruby and all things web development, make sure to follow me on Twitter where I post helpful articles and tips all the time.

Marketing and language expert

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store