Ruby - Check for Nil Without Using an Explicit If

Ruby - Check for nil Without Using an Explicit if

All checks for nil are a condition, but Ruby provides many ways to check for nil without using an explicit if. Watch out for nil conditional checks behind other syntax:

Explicit if with nil?

1
2
3
4
5
if listing.nil?
  nil
else
  listing.name
end

Using other syntax:

Implicit nil check through truthy conditional

1
2
3
if listing
  listing.name
end

Relies on nil being falsey

1
listing && listing.name

Call to try

1
listing.try(:name)