Test if string is not equal to either of two strings

匆匆过客 提交于 2019-12-04 16:28:03

问题


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?


回答1:


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" %>



回答2:


<% unless ['sessions', 'registrations'].include?(controller_name) %>

or

<% if ['sessions', 'registrations'].exclude?(controller_name) %>


来源:https://stackoverflow.com/questions/16870540/test-if-string-is-not-equal-to-either-of-two-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!