Reputation: 53
I have this simple condition in my ruby code:
if user.text != ("Empty" || "Damaged")
do something...
the thing is that when it is "Damaged" it still enters the loop, so I have to use this:
if user.text != "Empty"
if user.text != "Damaged"
...
..
What is the correct syntax to make the first one work? Thanks!
Upvotes: 1
Views: 51
Reputation: 13925
Use this:
unless ["Empty", "Damaged"].include?(user.text)
...
end
The problem with your first approach is that a || b
means that: if a != nil
then it is a
, else it is b
. As you can see it is good for variables, not constants as they are rarely nil. Your expression ("Empty" || "Damaged")
simply equals "Empty"
.
You want to use the this as a binary operator, the correct form would be:
if (user.text != "Empty") && (user.text != "Damaged")
The upper solution is just shorter. It consists of an array of elements you want to avoid, and you just simply check is the user.text
is not present in it.
Upvotes: 6
Reputation: 2386
@Matzi has the right answer, for sure. But here's why what you're doing is failing:
Your statement ("Empty" || "Damaged")
evaluates to "Empty"
You're saying return either one of these, whichever non-false thing you find first. In Ruby, any string, number or Object returns true, so you return "Empty" every time.
A better way to lay it out if you really want to use an if statement:
if user.text != "Empty" && user.text != "Damaged"
...
end
I assume, by the way, that you're trying to say "If the user text is neither Damaged nor Empty".
Hope that helps.
Upvotes: 2