Skip to content

Instantly share code, notes, and snippets.

@mrship
Created May 6, 2014 09:37
Show Gist options
  • Select an option

  • Save mrship/d0a3c50863856f3eb426 to your computer and use it in GitHub Desktop.

Select an option

Save mrship/d0a3c50863856f3eb426 to your computer and use it in GitHub Desktop.

try vs andand vs early return (x2)

Which is the preferred way to determine if a chained call is nil? i.e:

  1. company.andand.name
  2. company.try(:name)
  3. return nil if company.nil?; company.name
  4. (company or return nil).name

For the last one, you must use the predicate or rather than || to make the return work correctly.

@joaomilho
Copy link
Copy Markdown

class NullCompany
  def name
    'no company'
  end
end

company = some_logic? ? Company.new(some_data) : NullCompany
company.name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment