ruby, how to structure an if block with AND & OR
Right now I have the following:
<% if !@thread.nil? && @thread.name == 'X' || @thread.name == 'Y' %>
....
The problem here is that I believe regardless if !@thread.nil?, @thread.name is still be called which is causing errors.
What's the right way to write this so it's like:
<% if !@thread.nil? && @t开发者_Python百科hread.name == ('X' || 'Y') %>
Some type of contained in a list? for the thread.name?
Thanks
if !@thread.nil? && ['x','Y'].include?(@thread.name)
if @thread.present? and ['X', 'Y'].include?(@thread.name)
Edit: More info on #present?
.
The try method could make this code more clearer. Take a look at this http://everydayrails.com/2011/04/28/rails-try-method.html.
['x', 'Y'].include?(@thread.try(:name))
or
['x', 'Y'].include? @thread.try :name
精彩评论