TIP: if-else, case-when, hash?
One of the most primitive things you do when coding is writing if-else
conditionals.
When I just started, this looked perfect to me:
1. 2015: If-Elsif
#
# app/models/task.rb
class Task < ApplicationRecord
def status_color(status)
if status == 'incoming'
'grey'
elsif status == 'todo'
'orange'
elsif status == 'done'
'green'
elsif status == 'spam' || status == "error"
'red'
else
'black'
end
end
end
Task.status_color('done')
=> 'green'
One beautiful day, I learnt about
Rubocop
and it introduced me to
case-when
2. 2017: Case-When
#
# app/models/task.rb
class Task < ApplicationRecord
def status_color(status)
case status
when 'incoming'
'grey'
when 'todo'
'orange'
when 'done'
'green'
when 'spam', 'error'
'red'
else
'black'
end
end
end
Task.status_color('done')
=> 'green'
A bit cleaner and less duplication, right?
However, in some cases you can just define a hash
and get a value from a hash:
3. 2021: hash[key] => value
#
# app/models/task.rb
class Task < ApplicationRecord
COLOR_STATUSES = { incoming: 'grey', todo: 'orange', done: 'green', spam: 'red', error: 'red' }.freeze
end
Task::COLOR_STATUSES['todo'] || 'black'
=> 'orange'
# Task::COLOR_STATUSES[@task.status.to_sym] || 'black'
In some cases this is better and simpler!
Here’s a real-world scenario where this approach is better (kudos @secretpray)
Did you like this article? Did it save you some time?