Idiomatic Ruby: writing beautiful code
Ruby is a beautiful programming language
Ruby is a “dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.” created by Matz, a Japanese software engineer, the Ruby chief designer & software engineer @heroku since 2011.
He has often said that he is “trying to make Ruby natural, not simple” in a way that mirrors life.
Ruby is simple in appearance, but is very complex inside, just like our human body — Matz
I feel the same way about Ruby. A complex, but very natural programming language, with a beautiful & intuitive syntax.
As I think the more intuitive & faster the code is, a better software we’re building, in this post, I want to show you how I express my thoughts (A.K.A code) using Ruby in little snippets of code.
Expressing my thoughts with Array Methods
Using map to simplify your code, and get what you want. Map “returns a new array with the results of running block once for every element in enum”. Let’s try it:
Simple as that! But when you begin with ruby, it is easy to always use the each iterator. This “each iterator code”…
… can be simplified with map in a single beautiful line of code:
Or even better (and faster):
And when you’re used to code with map, sometimes your code can be like that:
Using map to select only the even numbers returns the nil object as well. So you use compact method to remove all nil objects. And TADA, you selected all even numbers. Mission Accomplished!
Come on, we can do better than this! Did you hear about select method from Enumerable module?
Just one line. Simple code. Easy to understand.
Imagine for some reason, you need to get a random element from an array. You just started learning ruby, so your first thought you’ll 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 shuffle method?
Hmm. I actually prefer shuffle instead of using rand. But when I discovered sample method it made so much 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 let me code. It’s really natural for me. I’ll show parts of the beautiful Ruby syntax.
Any statement in ruby returns the value of the last evaluated expression. A simple example is a getter method. We call a method and expect some value in return. Let’s see:
But as we know that ruby always returns the last evaluated expression, why use the “return” statement?
After 3 years using Ruby, I feel great using almost every method without the “return” statement.
Ruby allows me to assign multiple variables in the same time. When you begin, you maybe code like this:
But why not assign multiple variables in the same time?
Method that ask question (also called Predicates)
One of all Ruby features that took my attention when I began was the “question mark (?)” in methods (predicates methods). In the first time, it was weird to see, but now it makes so much sense. You can write code like that:
Ok… nothing wrong with that. But let’s use question mark:
This way is much more expressive and I expect that the method answers with a true / false value.
A method that I commonly use is “any?” method. It’s like asking for an array if it has anything inside it.
For me string interpolation is more intuitive than string concatenation. Period. Let’s see it in action
I prefer string interpolation. What do you think about that?
One way I really like to use Ruby If statement:
Pretty nice to code like that. Feel so natural.
Try (Rails mode on)
Try method invokes the method identified by the symbol method, passing it any arguments and/or the block specified, just like Ruby Object#send. Unlike that method, nil will be returned if the receiving object is a nil object or NilClass.
Using if/unless condition statement:
Using try method:
Since Ruby 2.3, we can use Ruby 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 if statement at all. Just double pipe equals and it’s done! Simple and easy.
Class Static Method
One way I like to write Ruby classes is defining 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 & Setters
For the same GetSearchResult class, if we want to use the params, we can use the @ params
We define a setter / getter for this instance variable
Or we can define attr_reader, attr_writer or attr_accessor
Nice! We don’t need to define getter and setter methods. The code became simpler as we like.
Imagine you want to define a create_user method. This method will instantiate, set the parameters, save and return the user. Let’s do it!
Simple. Nothing wrong here. So now let’s implement it with tap method
You just need to worry about the user parameters, and tap method will return the user object for you.
We learnt a lot of things about how I write Idiomatic Ruby:
- How I code with Ruby array methods
- How I code with Ruby syntax
- How Ruby can be more beautiful & intuitive (and even faster!)
And that’s it guys! I want to update (include more details) that blog post. The idea is to share a great content and the community helps improving this post! ☺
I hope you guys could appreciate the content and learnt more about how we can program beautiful code (and better softwares).
Have fun, keep learning & always coding!