Is using more number of if/else blocks a bad practice? Should we break it down to ternary operators or ruby specific unless operator?
I think that, like anything else, being clear to your future self is most important. Sure, if you're writing some tight, critical loop, then go with the most performant code, but overall neatness matters. I happen to like ternary operators quite a bit but they can get a bit tricky and convoluted if you let them.
Prashant Abhishek
Co-founder at AltCampus
Generally speaking, if you happen to write tons of if-else blocks in ruby that means there could be a room for improvement, improvements are generally fine grained and goes unnoticed unless pointed by someone else.
There are a few patterns and tips for this case.
Using guard clauses is one of the most important. Here's a good post by Martin Fowler explaining it- refactoring.com/catalog/replaceNestedConditionalW…
Use Try instead of conditionals to handle 'nil' replace
@user ? @user.name : nilwith@person.try(:name)Use Polymorphism to avoid if-else.
Using simple example- instead of
use
This is darn simple, but you can read more on this here- Thoughtbot's blog
However these are little tips and tricks. For a thorough understanding of nuances like this and OOP, I would recommend reading- Practical Object oriented design in Ruby by Sandi Metz and Refactoring: Improving the Design of Existing Code by Martin Fowler