Category: Tips
-
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 Do’s
-
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 user[:profile][:address][:city] if user[:profile] && user[:profile][:address] Do’s
-
How To Merge Strings?
Use interpolation to merge strings instead of using concatenation. Comparatively, Interpolation would be faster than the concatenation. Don’ts Do’s
-
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 Do’s
-
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 Do’s
-
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)
-
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 Do’s Related: Top Companies That Use Ruby on Rails
-
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 Do’s
-
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 Do’s Don’ts Do’s