Ruby Pro Tip: Short Circuit Assignment
How not to conditionally set a variable:
if a.nil?
a = b
endInstead, you should use the ||= operator:
a ||= bBoth code blocks will do the same, but the second one is cleaner and way more readable. You might also at some point need to evaluate if B is nil and assign C to A if so, this is how not to do it:
if b.nil?
a = c
else
a = b
endOne could argue in favor of using a ternary operator instead, which is better but not ideal either:
a = b.nil? ? c : bWe can further simplify this expression by using the || operator instead:
a = b || cNow that’s how the cool kids do it!