Victor
Victor

Reputation: 13378

Comibine conditions in Ruby

Is there a better way to write this?

if a == 'new' || a == 'create'
  ...
else
  ...
end

Instead of checking a twice, I thought I could combine the first line with one a. I'm looking at something like:

if a == ['new' || 'create']

Upvotes: 2

Views: 92

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118271

yes there is :

if %w(new create).include? a
  #code here
else
  #code
end

Upvotes: 3

the Tin Man
the Tin Man

Reputation: 160551

It's possible to do the test several ways, but doing it on a single line isn't necessarily the best idea. One of the clearest ways to write it in Ruby is to use a case statement:

case a
when 'new', 'create'
  ...
else
  ...
end

The advantage to doing this is you can easily add additional tests by appending them to the when list.

You could get down and dirty with a regex:

%w[foo renew new created create].each do |w|
  puts w[/^(?:new|create)$/]
end

Which would generate output like:

# >> 
# >> 
# >> new
# >> 
# >> create

# >> is the output marking a new line when using Sublime Text. This means only new and create matched.

I don't especially recommend that unless you understand regular expressions, but it can be an extremely fast way to check against a huge number of options.

Upvotes: 6

Related Questions