Hash Fetch Instead of If/Else
Conditional logic has its place, but often there’s a better alternative. Today, we’ll look at a Ruby solution: a hash with .fetch. My thanks to Brian Dunn, who showed me the value of this technique. Imagine you have a method that translates some data, a symbol for a role, into a presentation. A conditional is a popular solution here: def display_name(role) if role == :customer 'angler' elsif role == :employee 'guide' else name.to_s end end I think this method is much improved as a hash: ...