Skip to content

Instantly share code, notes, and snippets.

@georgeguimaraes
Created September 1, 2010 17:11
Show Gist options
  • Save georgeguimaraes/561024 to your computer and use it in GitHub Desktop.
Save georgeguimaraes/561024 to your computer and use it in GitHub Desktop.
And Begin Idiom to avoid if with assignments
# 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!
@dui
Copy link

dui commented Sep 1, 2010

and the only reason why 'and' even exists in ruby is the fact that it has a different precedence to '&&', so I don't think its a good reason not to use it, unless you want to argue using 'and' is never a good idea.

@rogerleite
Copy link

I prefer the first case. Like hugobarauna said.

@danielvlopes
Copy link

Pretty good. Both have use cases depending on the situation.

@dirceu-jr
Copy link

cool

@fnando
Copy link

fnando commented Sep 1, 2010

I'll go with assignment then checking.

variable = expression(something)
if variable
end

Can't be easier to read than that.

@smsohan
Copy link

smsohan commented Sep 1, 2010

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.

@evanphx
Copy link

evanphx commented Sep 1, 2010

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.

@danielvlopes
Copy link

Thinking in that way I agree with @evanphx. Second syntax is not common and most of people we don't know how it works.

@raggi
Copy link

raggi commented Sep 2, 2010

i prefer the if, by far.

@pahagon
Copy link

pahagon commented Sep 2, 2010

In the second, there seems to be a condition

@sferik
Copy link

sferik commented Jul 25, 2011

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