-
-
Save tomafro/561112 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
# After reading this comment | |
# http://avdi.org/devblog/2010/08/02/using-and-and-or-in-ruby/#comment-1098 , | |
# | |
# I became aware of a cool idiom for Ruby. | |
# | |
# I've seen this in a lot of cases: | |
if (variable = expression_or_method(options)) | |
variable.calculate_something | |
do_other_stuff(variable) | |
end | |
# This is another way to code the same concept: | |
variable = expression_or_method(options) and begin | |
variable.calculate_something | |
do_other_stuff(variable) | |
end | |
# The former case issues a warning because we're using = in an if statement. | |
# The latter seems more semantic to me too. | |
# What do you think??? Comments below! | |
# Another more explicit alternative (though I prefer the first option): | |
unless (variable = expression_or_method(options)).nil? | |
variable.calculate_something | |
do_other_stuff(variable) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment