Topic: Specifying Multiple Conditions

Right now I have a piece of code that works, but I am convinced there is a more idiomatic way to write it

if @current_action == 'edit' || @current_action == 'new' || @current_action == 'create'  || @current_action == 'update'
   "something"
else
   "something else"
end

I have tried specifying multiple strings and || operators after that == but it only workswhen I do it longhand like this.

How should I clean this up?

Re: Specifying Multiple Conditions

What about a regex?

if @current_action =~ /[edit|new|create|update]/
   "something"
else
   "something else"
end

Something like that.

Re: Specifying Multiple Conditions

Try this:

if %w[edit new create update].include? @current_action
  "something"
else
  "something else"
end

The %w[] thing puts the words in an array of strings and the .include? method will check if the given parameter is in that array.

Railscasts - Free Ruby on Rails Screencasts

Re: Specifying Multiple Conditions

Both of those are just great. Thanks guys!

Re: Specifying Multiple Conditions

pimpmaster wrote:

Both of those are just great. Thanks guys!

For anyone coming to this thread after:

Go for Ryan's solution.  My solution will match values like 'ew', 'at', etc. because they are contained in the words (I'm sure there's a better way to do it with regex's, that's just the first thing to pop into my mind).

Also, Ryan's solution is roughly 3 times faster (according to my lazy benchmarking):

@word = 'create'
time = Time.now

if @word =~ /[create]|[edit]|[update]|[destroy]/
  puts "Blah!"
  puts Time.now - time
else
  puts "Meh."
end

time = Time.now

if %w{create edit update destroy}.include?(@word)
  puts "Blah!"
  puts Time.now - time
else
  puts "Meh."
end


Will output (something like):

Blah!
3.0e-05
Blah!
1.0e-05

EDIT
Found my mistake:
It should be:

if @word =~ /create|edit|update|destroy/

It also speeds it up a little, but Ryan's is still faster.
(It's now about 2.5e-05 to 1.0e-05)

Last edited by Firanide (2007-05-06 02:05:03)