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!
@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