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! |
Heavily dislike the 2nd syntax. It's extremely clever and hard to read. You should be asking yourself: Will the next person to read this code have a clear idea what I've done? I can't see yes being the answer.
Thinking in that way I agree with @evanphx. Second syntax is not common and most of people we don't know how it works.
i prefer the if, by far.
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
While the 2nd syntax is new to me and sounds "Techy" - I would still take the simple approach of assigning first and then checking. It way more readable to me this way.