Idiomatic Ruby: writing beautiful code

Ruby is a beautiful programming language.

According to Ruby’s official web page, Ruby is a:

Ruby was created by Yukihiro Matsumoto, a Japanese software engineer. Since 2011, he has been the chief designer & software engineer for Ruby at Heroku.

Matsumoto has often said that he tries to make Ruby natural, not simple, in a way that mirrors life.

I feel the same way about Ruby. It is a complex but very natural programming language, with a beautiful and intuitive syntax.

With more intuitive and faster code, we are able to build better software. In this post, I will show you how I express my thoughts (aka code) with Ruby, by using snippets of code.

Expressing my thoughts with array methods

Map

Use the map method to simplify your code and get what you want.

The method map returns a new array with the results of running a block once for every element in enum.

Let’s try it:

Simple as that.

But when you begin coding with Ruby, it is easy to always use the each iterator.

The each iterator as shown below

Can be simplified with map in a single beautiful line of code:

Or even better (and faster):

Select

And when you’re used to coding with map, sometimes your code can be like this:

Using map to select only the even numbers will return the nil object as well. Use the compact method to remove all nil objects.

And ta-da, you’ve selected all the even numbers.

Mission accomplished.

Come on, we can do better than this! Did you hear about the select method from enumerable module?

Just one line. Simple code. Easy to understand.

Bonus

Sample

Imagine that you need to get a random element from an array. You just started learning Ruby, so your first thought will be, “Let’s use the random method,” and that’s what happens:

Well, we can understand the code, but I’m not sure if it is good enough. And what if we use the shuffle method?

Hmm. I actually prefer to use shuffle over rand. But when I discovered the sample method, it made so much more sense:

Really, really simple.

Pretty natural and intuitive. We ask a sample from an array and the method returns it. Now I’m happy.

What about you?

Expressing my thoughts with Ruby syntax

As I mentioned before, I love the way Ruby lets me code. It’s really natural for me. I’ll show parts of the beautiful Ruby syntax.

Implicit return

Any statement in Ruby returns the value of the last evaluated expression. A simple example is the getter method. We call a method and expect some value in return.

Let’s see:

But as we know, Ruby always returns the last evaluated expression. Why use the return statement?

After using Ruby for 3 years, I feel great using almost every method without the return statement.

Multiple assignments

Ruby allows me to assign multiple variables at the same time. When you begin, you may be coding like this:

But why not assign multiple variables at the same time?

Pretty awesome.

Methods that ask questions (also called predicates)

One feature that caught my attention when I was learning Ruby was the question mark (?) method, also called the predicates methods. It was weird to see at first, but now it makes so much sense. You can write code like this:

Ok… nothing wrong with that. But let’s use the question mark:

This code is much more expressive, and I expect the method’s answer to return either a true or false value.

A method that I commonly use is any? It’s like asking an array if it has anything inside it.

Interpolation

For me string interpolation is more intuitive than string concatenation. Period. Let’s see it in action.

An example of a string concatenation:

An example of a string interpolation:

I prefer string interpolation.

What do you think?

The if statement

I like to use the if statement:

Pretty nice to code like that.

Feels really natural.

The try method (with Rails mode on)

The try method invokes the method identified by the symbol, passing it any arguments and/or the block specified. This is similar to Ruby’s Object#send. Unlike that method, nil will be returned if the receiving object is a nil object or NilClass.

Using if and unless condition statement:

Using the try method:

Since Ruby 2.3, we can use Ruby’s safe navigation operator (&.) instead of Rails try method.

Double pipe equals (||=) / memoization

This feature is so C-O-O-L. It’s like caching a value in a variable.

You don’t need to use the if statement ever. Just use double pipe equals (||=) and it’s done.

Simple and easy.

Class static method

One way I like to write Ruby classes is to define a static method (class method).

Simple. Beautiful. Intuitive.

What happens in the background?

The self.call method initializes an instance, and this object calls the call method. Interactor design pattern uses it.

Getters and setters

For the same GetSearchResult class, if we want to use the params, we can use the @params

We define a setter and getter:

Or we can define attr_reader, attr_writer, or attr_accessor

Nice.

We don’t need to define the getter and setter methods. The code just became simpler, just what we want.

Tap

Imagine you want to define a create_user method. This method will instantiate, set the parameters, and save and return the user.

Let’s do it.

Simple. Nothing wrong here.

So now let’s implement it with the tap method

You just need to worry about the user parameters, and the tap method will return the user object for you.

That’s it

We learned I write idiomatic Ruby by coding with

  • array methods
  • syntax

We also learned how Ruby is beautiful and intuitive, and runs even faster.

And that’s it, guys! I will be updating and including more details to my blog. The idea is to share great content, and the community helps to improve this post! ☺

I hope you guys appreciate the content and learned how to program beautiful code (and better software).

If you want a complete Ruby course, learn real-world coding skills and build projects, try One Month Ruby Bootcamp. See you there ☺

This post appeared first here on my Renaissance Developer publication.

Have fun, keep learning, and always keep coding!

My Twitter & Github. ☺

--

--

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