Skip to content

Instantly share code, notes, and snippets.

@tomafro
Forked from georgeguimaraes/and_begin_idiom.rb
Created September 1, 2010 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomafro/561112 to your computer and use it in GitHub Desktop.
Save tomafro/561112 to your computer and use it in GitHub Desktop.
# 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