Emmanuel Pastor bio photo

Emmanuel Pastor

Software polymath, application architect, code craftsman.

Twitter

LinkedIn

Github

Ruby Pro Tip: Short Circuit Assignment

How not to conditionally set a variable:

if a.nil?
a = b
end

Instead, you should use the ||= operator:

a ||= b

Both 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
end

One could argue in favor of using a ternary operator instead, which is better but not ideal either:

a = b.nil? ? c : b

We can further simplify this expression by using the || operator instead:

a = b || c

Now that’s how the cool kids do it!



comments powered by Disqus