Skip to content

Instantly share code, notes, and snippets.

@alloy
Forked from jeffkreeftmeijer/options.rb
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alloy/22dca640788e22f8bd0c to your computer and use it in GitHub Desktop.
Save alloy/22dca640788e22f8bd0c 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
# Option 5 (readability, but still scratching that DRY itch)
info = if publication
"Title: #{ publication.title } (ID: #{ publication.id })"
else
'N/A'
end
@PericlesTheo
Copy link

I personally stopped using the ternary operator for 2 reasons:

  1. I don't actually think it makes things more readable
  2. It hides complexity

Re the second reason I have actually seen people using them in nested conditionals pretending that it's a one-liner.

if ...
  ...
else
  publication ? "Title: #{ publication.title } (ID: #{ publication.id })" : 'N/A'
end

Of course the tools are as good as we are but I kind of prefer the explicitly of if/else in most cases.

I will use it in cases like user ? do_some : some_else where the methods/variables in this case are already defined somewhere else.

WDTY?

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