Functions in Ruby that make life easy.

I have been using ROR for the last eight months and started loving this language because of the poetic way it allows me to write the code.

'log_error('Log message') and return if data.blank?'

In this journey, I have found some functions which helped me to keep the code short and improved readability significantly.

1. blank? and present?

A common use case while writing code is you have to check if a variable is null or contains valid data.

blank? – returns true in case of empty string, array, hash, and nil values
present? – returns true if it has valid data

2. each, inject, map

I rarely use a for loop in my code, in the case of a list of items these functions are enough to iterate through them, and functions like inject and map are highly recommended if you are writing one line condition.

Read Also: Reload in ruby and when to use it.

3. to_h, to_a, to_f

These functions are saviors, I use them as optional chaining in rails, if I want to access a hash, array without worrying about getting this error.

undefined method for nil:nilClass

they are my go-to function helps me to keep the code short

4. ||

This is an awesome function saved around 20-30 lines of code, the use case was in a function consider.

def assign(data, type)
  location = ''
  if type == 'plane'
    location = data[:airport]
  elsif type == 'ocean'
    location = data[:port]
  elsif type == 'road'
    location = data[:pincode]
  end
  # Do something with loaction
end

Read Also: Demystifying ActiveRecord query generation – Arel

Using ||

def assign (data, type)
  location =  data[:airport] || data[:port] || data[:pincode]
  # do something with location
end

Thank you for your time.

Related Post