Devtechnica

Code, Computers & Beyond.

A Collection of Tips and Tricks For The Ruby Language

5 min read

Ruby is a boon to software developers. Its design simplifies the process of creating a program letting its developers spend more time on the algorithm and functionality rather than the code itself. I have been using Ruby for years now and in this article, I’ve decided to share some of Ruby’s most interesting yet not widely known features so that developers new to the Ruby language could benefit from it. So let’s dive right into some of Ruby’s most interesting Tips and Tricks.

This article will be updated regularly to include more ruby tips and tricks as I discover more.

1. Passing Methods as Procs to Functions

Ruby lets methods/functions accept codeblocks as arguments to be used inside it. But did you know that methods can be passed in as procs too? All objects in Ruby have a method called “method”. This method accepts the name of a method that is callable on the object and returns that method as a proc which can be passed into other methods that accept codeblocks as arguments. An example of this would be:

require 'date'
["11/06/2018", "01/01/2019"].map(&Date.method(:parse))
[#<Date: 2018-06-11 ((2458281j,0s,0n),+0s,2299161j)>, #<Date: 2019-01-01 ((2458485j,0s,0n),+0s,2299161j)>]

In the code above, We have used the method function to get the parse method of the Date class as a Proc and passed the proc into the map method. This will return an array of Date objects created from the array of date strings.

This is a very useful trick to make your code look a little cleaner.

2. Converting a String into Boolean – Rails Only

Converting a string value to a Boolean value can be quite tricky especially when creating web applications. You might receive a Boolean value passed into the application through the URL as a string (e.g: “true” or “false”). Rails has a neat solution to solve this problem. You can easily convert the “true” or “false” string into a Boolean value using:

ActiveRecord::Type::Boolean.new.cast("true") #=> true
ActiveRecord::Type::Boolean.new.cast("false") #=> false
ActiveRecord::Type::Boolean.new.cast(nil) #=> false

Using this method, any value in [“false”, “False”, “FALSE”, nil, 0, “0”, “f”, “F”, “off”, “OFF”] when passed into the above method will return false. Any value other than the ones specified above will return true.

3. Using the Tap Method

tap method is very useful when chaining methods together. The tap method accepts a codeblock for an argument and then returns the object itself regardless of the return value of the codeblock. This is useful to build method chains without breaking the chain because of an unfavorable return value of a single method. An example use-case of this would be:

file = File.open('devtechnica.txt', 'r')
content = file.readlines
content_repeat = file.tap(&:rewind).readlines

Typically, the rewind method when called on a file IO will return the buffer offset after resetting it, which is always 0. this will break the chain and will not let us chain the readlines method to it. By using the rewind method inside a tap method block, which returns the object on which it is called, we are able to chain the readlines method as well.

4. The Safe Navigation Operator (&)

Running into an “Undefined method for nil class” exception during development is very common especially in web applications where the expected parameters might not be passed into the request. The old and inconvenient way of handling this would be to use the “try” method. Since Ruby 2.3.0, a new way to handle this was introduced, the Safe Navigation Operator “&”. This allows you to call a method only when an object is not nil. For example:

require 'ostruct'
person = OpenStruct.new
person.name, person.address = "sreedev", nil

# old way
upcase_address = person.address && person.address.upcase

# using the safe navigation operator
upcase_address = person.address&.upcase

Using the safe navigation operator lets you escape the nil exception without making your code look bad.

5. Using Hash#fetch for Retrieving Hash Values

Hash#fetch is a way of retrieving a value from a hash based on a key. The advantage of using the fetch method is that you can specify a default value to be returned in case the key passed in does not exist in the hash. This is very useful and makes your code look cleaner.

new_hash = {name: "Sreedev"}

# without using Hash#fetch
lang = new_hash[:language] ? new_hash[:language] : "Ruby"

# Using Hash#fetch
lang = new_hash.fetch(:language, "Ruby")

Please note that fetch will only return the default value when the key is not defined in the hash.

Getting Name of Associated Models in Rails

Having to reopen the model every time you need to see the associations of the model, is time consuming. You can easily look up all Model Classes that a particular model is associated with in the following method through the rails console.

Post.reflect_on_all_associations.map(&:class_name)

Further, you can specify a type of association as a parameter to the method. An example of this would be:

Post.reflect_on_all_associations(:has_one).map(&:class_name)

Those are the top tips and tricks I’ve discovered over the years working with the Ruby programming language to write clean and maintainable code. I shall keep this article updated to include any new features, tips or tricks that I come across in the future. You may submit your Ruby programming tips to DevTechnica and I shall include them here.