Skip to content

Instantly share code, notes, and snippets.

@jeffkreeftmeijer
Forked from andremedeiros/options.rb
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeffkreeftmeijer/99ac66a9665ae8cc6b12 to your computer and use it in GitHub Desktop.
Save jeffkreeftmeijer/99ac66a9665ae8cc6b12 to your computer and use it in GitHub Desktop.
# Option 1
info = if publication
"Title: #{ publication.title } (ID: #{ publication.id })"
else
'N/A'
end
# Option 2
info = case publication
when Publication then puts "Title: #{ publication.title } (ID: #{ publication.id })"
when nil then puts 'N/A'
end
# Option 3 (brevity)
info = publication ? "Title: #{ publication.title } (ID: #{ publication.id })" : 'N/A'
# Option 4 (readability)
if publication
info = "Title: #{ publication.title } (ID: #{ publication.id })"
else
info = 'N/A'
end
@chastell
Copy link

class Publication
  def info
    "Title: #{title} (ID: #{id})"
  end
end

class NullPublication
  def info
    'N/A'
  end
end

# ideally somewhere much earlier in the system
publication ||= NullPublication.new

info = publication.info

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