Skip to content

Instantly share code, notes, and snippets.

@robbyrussell
Created August 20, 2010 23:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robbyrussell/541438 to your computer and use it in GitHub Desktop.
Save robbyrussell/541438 to your computer and use it in GitHub Desktop.
# just showing one of our designers how to tighten up some conditionals..
if @foo == "bar" || @foo == "baz" || @foo == "meep"
# do something
end
# can also be written like so...
if ["bar", "baz", "meep"].include?(@foo)
# do something
end
# basically, this says... dear ruby, if this collection of strings contains the value of @foo... do the following
# another suggestion
if %w(bar baz meep).include?(foo)
# do something..
end
@michaeldv
Copy link

BTW, the fastest and shortest is regex match:

require "benchmark"

Benchmark.bm do |x|
     x.report { 100_000.times { puts 'match' if @foo == "bar" || @foo == "baz" || @foo == "meep" } }
     x.report { 100_000.times { puts 'match' if ["bar", "baz", "meep"].include?(@foo) } }
     x.report { 100_000.times { puts 'match' if %w(bar baz meep).include?(@foo) } }
     x.report { 100_000.times { puts 'match' if @foo =~ /bar|baz|meep/ } }
end

@wajiii
Copy link

wajiii commented Aug 21, 2010

Wow, that's quite a difference. Thanks, Michael!

@BMorearty
Copy link

If

["bar", "baz", "meep"].include?(@foo)

feels backwards, try my in_enumerable gem and write it as

@foo.in?(["bar", "baz", "meep"])

@wajiii
Copy link

wajiii commented Aug 22, 2010

I should add that in my testing, the regex is only the fastest if @foo is not "bar" or "baz", so one should still take the usual care in choosing the condition (and possibly ordering) that best suits the expected data.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment