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 : nil with @person.try(:name)
Use Polymorphism to avoid if-else.
Using simple example-
instead of
class Animal
def initialize(name, type)
@name = name
@type = type
end
def introduce
puts "Hello, I am #{@name}"
end
def speak
if @type == "Dog"
puts "Hello, I bark."
elsif @type == "Cat"
puts "Hello, I meow."
elsif @type =="Lion"
puts "Hello, I roar."
else
puts "Hello, I am a human and I shout! ;)"
end
end
dexter = Animal.new("Dexter", "Cat")
dexter.speak("Cat")use
class Animal
def initialize(name)
@name = name
end
def introduce
puts "Hello, I am #{@name}"
end
def speak
puts "Hello, I am a human and I shout! ;)"
end
end
class Dog < Animal
def speak
puts "Hello, I bark."
end
end
class Cat < Animal
def speak
puts "Hello, I meow."
end
end
class Lion < Animal
def speak
puts "Hello, I roar."
end
end
dexter = Cat.new("Dexter")
dexter.speakThis 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