-
-
Save alloy/22dca640788e22f8bd0c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I personally stopped using the ternary operator for 2 reasons:
Re the second reason I have actually seen people using them in nested conditionals pretending that it's a one-liner.
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?