At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

Top 10 Ruby Tricks For Enhanced Performance

  • By Saravana
  • July 31, 2018
  • 2342 Views

In our previous blog, we have clearly explained about the 10 must use ruby on rails tips and tricks that developers must follow. Based on the significant interests and reach of that blog here we are revealing another set of Ruby tricks and standard practices that will help you to improve the code and also the performance of your application. Along with the tricks, sharing with you the do ‘s and dont’s of Ruby in brief and hoping that it could make your Ruby application to perform better.

1) Use Fetch To Find Value From The Hash

Using hash[] method we can return the value. It will return the value if the key exists, else it will return nil.
Using hash fetch method will also do the same but additionally, it will give few options like assigning a default value, executing block, etc.
Here are some examples

Don’ts

hash = { one: "one", two: "two", three: "three" }
hash[:one] -> one\

Do’s

hash = { one: "one", two: "two", three: "three" }
hash.fetch(:one) - > one

Don’ts

hash = { one: "one", two: "two", three: "three" }
value = hash[:four] ? hash[:four] : 4
puts value -> 4

OR other

hash = { one: "one", two: "two", three: "three" }
value = hash[:four] || 4
puts value -> 4

Do’s

hash = { one: "one", two: "two", three: "three" }
value = hash.fetch(:four, 4)
puts value - > 4

2) Mass Variable Assignments

Mass assignment is a useful feature to assign multiple variables in a single place. We can use it to return the multiple values from the method and this returned value can be assigned by Mass variable assignments.

Don’ts

one = 1
two = 2
three = 3

Do’s

one, two, three = 1, 2, 3

3) Use the .map Method To Iterate And To Return Modified Object

Developers have to understand the difference between .map and .each methods. When using these functions try to choose the appropriate method based on the situations.
For example, If you want to return the vowels array in the capital letter then use .map method,

Don’ts

vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
new_vowels = []
vowels = vowels.each { |vowel| new_vowels << vowel.upcase }
puts new_vowels -> [‘A’, ‘E’, ‘I’, ‘O’, ‘U’]

Do’s

vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
new_vowels = vowels.map { |vowel| vowel.upcase }
puts new_vowels -> [‘A’, ‘E’, ‘I’, ‘O’, ‘U’]

Related: Top Companies That Use Ruby on Rails

4) Try To Use “Ternary” Operator

Many developers will use the “if-else” statement for single line functions, For example,

def role(admin)
if admin == "admin"
return true
else
return false
end
end

Why we don’t start using a ternary here?

def role(admin)
admin == "admin" ? true : false
end

Another way to use the conditions as the return object.

def role(admin)
admin == "admin"
end

5) Use Rescue Blocks Properly

Rescue blocks always not required to use with ‘begin.’ If you are going to use only begin and rescue block in the method, then you can skip the begin.

Don’ts

def x
"a" + 1
rescue
puts "implicit conversion of Fixnum into String"
end

Do’s

def x
begin
"a" + 1
rescue
puts "implicit conversion of Fixnum into String"
end
end

6) Use .tap To Perform Operations And To Return The Object

Ruby .tap method is used to yields the object to the block and will return the modified object. For example,

Don’ts

def build_account
account = Account.new
account.name = "example"
account.email = "example@email.com"
account
end

Do’s

This method has a temporary variable to form and return the account object. We can change the above method just by using the .tap method.

def build_account
Account.new.tap do |user|
account.name = "example"
account.email = "example@email.com"
end
end

7) How To Merge Strings?

Use interpolation to merge strings instead of using concatenation. Comparatively, Interpolation would be faster than the concatenation.

Don’ts

puts “my name is ” + concatenation

Do’s

put “my name is #{interpolation}”
Interpolation supports “typecasting” but concatenation won’t support.

8) Retrieving The Nested Hash Value

Use hash dig method to get the nested hash values. Sometimes you have to navigate to multi-level hash to get values. For example, consider the below user hash.

Don’ts

users = [
{ profile: { name: "saran", address: { city: "chennai" } } },
{ profile: { name: "kumar" } }
]
user = users.first
user[:profile][:address][:city] => "chennai"
user = users.last
user[:profile][:address][:city] => NoMethodError: undefined method `[]' for nil:NilClass
[/code]
How we can avoid this error? Generally developers will add conditions like below,
[code]
user[:profile][:address][:city] if user[:profile] && user[:profile][:address]

Do’s

Ruby provides some special tricks to handle this situation.

user = users.first
user.dig(:profile, :address, :city) => "chennai"
user = users.last
user.dig(:profile, :address, :city) => nil

Related: Why Ruby on Rails is Perfect for E-Commerce Development

9) Using & To Create Procs

In many cases developers will use the map method with the block for doing simple operations, instead, they can use “& operator” for better code.

Don’ts

vowels = ['a','b','c']
new_vowels = vowels.map(&:upcase)
puts new_vowels -> [‘A’, ‘E’, ‘I’, ‘O’, ‘U’]

Do’s

vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
new_vowels = vowels.map { |vowel| vowel.upcase }
puts new_vowels -> [‘A’, ‘E’, ‘I’, ‘O’, ‘U’]

10) Use Bang! Methods

You can avoid the duplicate objects by using bang methods,

Don’ts

hash = { one: "one", two: "two"}
puts hash.merge(three: "three" ) - > {:one=>"one", :two=>"two", :three=>"three"}
puts hash -> {:one=>"one", :two=>"two"}
# here you have to assign merged value in a new variable
new_hash = hash.merge(three: "three" )
puts hash -> {:one=>"one", :two=>"two", :three=>"three"}

Do’s

hash = { one: "one", two: "two", three: "three" }
puts hash.merge!(three: "three" ) - > {:one=>"one", :two=>"two", :three=>"three"}
puts hash -> {:one=>"one", :two=>"two", :three=>"three"}

Hence we can avoid the redundancies or reduce creating multiple objects by using the bang methods.

The end

Hopefully, trying these Ruby tricks will make a convenient work phase for you. So try it out and share it with your friends so they can also learn. If you also know some helpful Ruby tricks then do share with us in the comment section so that everyone around the Ruby community can learn together. Similarly, find more informative blogs on our largest blog repository,
Stay updated with the latest topics & tricks and don’t forget to subscribe us to get the latest updates from diverse technologies. Besides all, Post us your valuable thoughts in the comment section.
For any queries reach us via info@agiratech.com.

Looking for a Tech partner to dominate the digital world?

Saravana

An enthusiastic Tech Lead with 7 plus years of experience in Web development arena. Owns legitimate experience in Ruby, Ruby On Rails, AngularJs, DevOps. Golang, Another add on, This young tech freak never miss a chance to get his hands on planting and Gardening even in his busy weekends.