user1337902 user1337902 - 4 months ago 9
Ruby Question

replace ternary nil check with ruby best practices

i find myself doing this quite a lot to protect against nil when the return of some_method returns nil.

a = a.some_method.present? ? a.some_method : []


is there a more ruby way to do it? I've tried using

a = []
a ||= a.some_method


but ofcourse that will just give me

a = []


thanks!

Answer

The usual pattern is:

result = method(args) || default_value

The || operator is short-circuiting. If the left-hand-side is false, it will not bother to evaluate the right hand side. In Ruby, nil is considered false. Hence if nil is returned (or false), the || evaluates the right-hand-side and returns that as the result.

Note the order of the left and right sides is important.