user1337902 user1337902 -5 years ago 127
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 = []


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download