AnApprentice
AnApprentice

Reputation: 111030

ruby, how to structure an if block with AND & OR

Right now I have the following:

<% if [email protected]? && @thread.name == 'X' || @thread.name == 'Y' %>
 ....

The problem here is that I believe regardless if [email protected]?, @thread.name is still be called which is causing errors.

What's the right way to write this so it's like:

<% if [email protected]? && @thread.name == ('X' || 'Y') %>

Some type of contained in a list? for the thread.name?

Thanks

Upvotes: 2

Views: 154

Answers (4)

DigitalRoss
DigitalRoss

Reputation: 146123

['x', 'Y'].include?(@thread.try(:name))

or

['x', 'Y'].include? @thread.try :name

Upvotes: 3

Chris Ledet
Chris Ledet

Reputation: 11628

if @thread.present? and ['X', 'Y'].include?(@thread.name)

Edit: More info on #present?.

Upvotes: 4

Mchl
Mchl

Reputation: 62395

if [email protected]? && ['x','Y'].include?(@thread.name)

Upvotes: 7

lucapette
lucapette

Reputation: 20724

The try method could make this code more clearer. Take a look at this http://everydayrails.com/2011/04/28/rails-try-method.html.

Upvotes: 3

Related Questions