Created
September 1, 2010 17:11
-
-
Save georgeguimaraes/561024 to your computer and use it in GitHub Desktop.
And Begin Idiom to avoid if with assignments
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! |
In the second, there seems to be a condition
Typically, when I'm doing something like this, I want to be able to specify an elsif
or else
condition, which isn't possible using begin
, for instance:
if rubygem = Rubygem.find_by_name(gem_name)
render :json => rubygem.public_versions
else
render :text => "This rubygem could not be found.", :status => 404
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i prefer the if, by far.