Test if string is not equal to either of two strings

PropSoft picture PropSoft · Jun 1, 2013 · Viewed 32.3k times · Source

I am just learning RoR so please bear with me. I am trying to write an if or statement with strings. Here is my code:

<% if controller_name != "sessions" or controller_name != "registrations" %>

I have tried many other ways, using parentheses and || but nothing seems to work. Maybe its because of my JS background...

How can I test if a variable is not equal to string one or string two?

Answer

Old Pro picture Old Pro · Jun 1, 2013

This is a basic logic problem:

(a !=b) || (a != c) 

will always be true as long as b != c. Once you remember that in boolean logic

(x || y) == !(!x && !y)

then you can find your way out of the darkness.

(a !=b) || (a != c) 
!(!(a!=b) && !(a!=c))   # Convert the || to && using the identity explained above
!(!!(a==b) && !!(a==c)) # Convert (x != y) to !(x == y)
!((a==b) && (a==c))     # Remove the double negations

The only way for (a==b) && (a==c) to be true is for b==c. So since you have given b != c, the if statement will always be false.

Just guessing, but probably you want

<% if controller_name != "sessions" and controller_name != "registrations" %>