Test Whether a Variable Equals Either One of Two Values

Test whether a variable equals either one of two values

Your first method is idiomatic Ruby. Unfortunately Ruby doesn't have an equivalent of Python's a in [1,2], which I think would be nicer. Your [1,2].include? a is the nearest alternative, and I think it's a little backwards from the most natural way.

Of course, if you use this a lot, you could do this:

class Object
def member_of? container
container.include? self
end
end

and then you can do a.member_of? [1, 2].

How do I test if a JS variable does equal either of two values?

I thought your original post was pretty straight forward and thought it was a perfectly fine answer to your problem.

Having said that you can use RegEx like @le_m mentioned. I just tested this in the console and this works.

The '//' tell the interpreter that we will be starting a regular expression. The parenthesis allow us to declare a subexpression. A subexpression that will be evaluated independently of other expressions.

The 'i' stands for insensitive. In this case it isn't entirely necessary but I think it might be useful for you down the road. The 'i' will allow you to avoid casing issues. Also, should you pass in longer strings that contain 'display', or 'type' in a sentence, this regex will also find those.

var type = 'display';
if (/(type|display)/i.test(type)) {
console.log('word found')
}

How do I test if a variable does not equal either of two values?

Think of ! (negation operator) as "not", || (boolean-or operator) as "or" and && (boolean-and operator) as "and". See Operators and Operator Precedence.

Thus:

if(!(a || b)) {
// means neither a nor b
}

However, using De Morgan's Law, it could be written as:

if(!a && !b) {
// is not a and is not b
}

a and b above can be any expression (such as test == 'B' or whatever it needs to be).

Once again, if test == 'A' and test == 'B', are the expressions, note the expansion of the 1st form:

// if(!(a || b)) 
if(!((test == 'A') || (test == 'B')))
// or more simply, removing the inner parenthesis as
// || and && have a lower precedence than comparison and negation operators
if(!(test == 'A' || test == 'B'))
// and using DeMorgan's, we can turn this into
// this is the same as substituting into if(!a && !b)
if(!(test == 'A') && !(test == 'B'))
// and this can be simplified as !(x == y) is the same as (x != y)
if(test != 'A' && test != 'B')

How to test multiple variables for equality against a single value?

You misunderstand how boolean expressions work; they don't work like an English sentence and guess that you are talking about the same comparison for all names here. You are looking for:

if x == 1 or y == 1 or z == 1:

x and y are otherwise evaluated on their own (False if 0, True otherwise).

You can shorten that using a containment test against a tuple:

if 1 in (x, y, z):

or better still:

if 1 in {x, y, z}:

using a set to take advantage of the constant-cost membership test (i.e. in takes a fixed amount of time whatever the left-hand operand is).

Explanation

When you use or, python sees each side of the operator as separate expressions. The expression x or y == 1 is treated as first a boolean test for x, then if that is False, the expression y == 1 is tested.

This is due to operator precedence. The or operator has a lower precedence than the == test, so the latter is evaluated first.

However, even if this were not the case, and the expression x or y or z == 1 was actually interpreted as (x or y or z) == 1 instead, this would still not do what you expect it to do.

x or y or z would evaluate to the first argument that is 'truthy', e.g. not False, numeric 0 or empty (see boolean expressions for details on what Python considers false in a boolean context).

So for the values x = 2; y = 1; z = 0, x or y or z would resolve to 2, because that is the first true-like value in the arguments. Then 2 == 1 would be False, even though y == 1 would be True.

The same would apply to the inverse; testing multiple values against a single variable; x == 1 or 2 or 3 would fail for the same reasons. Use x == 1 or x == 2 or x == 3 or x in {1, 2, 3}.

JavaScript: Simple way to check if variable is equal to one of two or more values?

You can stash your values inside an array and check whether the variable exists in the array by using [].indexOf:

if([5, 6].indexOf(x) > -1) {
// ...
}

If -1 is returned then the variable doesn't exist in the array.

Check variable equality against a list of values

Using the answers provided, I ended up with the following:

Object.prototype.in = function() {
for(var i=0; i<arguments.length; i++)
if(arguments[i] == this) return true;
return false;
}

It can be called like:

if(foo.in(1, 3, 12)) {
// ...
}

Edit: I came across this 'trick' lately which is useful if the values are strings and do not contain special characters. For special characters is becomes ugly due to escaping and is also more error-prone due to that.

/foo|bar|something/.test(str);

To be more precise, this will check the exact string, but then again is more complicated for a simple equality test:

/^(foo|bar|something)$/.test(str);

How to check if a variable is equal to one of two values using the if/or/and functions

The thing that is odd about GNUmake conditionals is that there is no boolean type in make -- everything is a string. So the conditionals all work with the empty string for 'false' and all non-empty strings (including strings like false and 0) as being 'true'.

That being said, the fact that eq is missing is an annoyonace albeit a minor one. Generally you can get what you want from filter or findstring, and filter often allows you to search a whole list of strings to match as in your second example.

If you really need it, you can define your own eq function:

eq = $(and $(findstring $(1),$(2)),$(findstring $(2),$(1)))

Which you unfortunately have to use as $(call eq,...,...)

Is there a simpler way to check multiple values against one value in an if-statement?

Unfortunately there is no such construct in Java.

It this kind of comparison is frequent in your code, you can implement a small function that will perform the check for you:

public boolean oneOfEquals(int a, int b, int expected) {
return (a == expected) || (b == expected);
}

Then you could use it like this:

if(oneOfEquals(a, b, 0)) {
// ...
}

If you don't want to restrict yourselft to integers, you can make the above function generic:

public <T> boolean oneOfEquals(T a, T b, T expected) {
return a.equals(expected) || b.equals(expected);
}

Note that in this case Java runtime will perform automatic boxing and unboxing for primitive types (like int), which is a performance loss.

How to check variable against 2 possible values?


if s in ('a', 'b'):
return 1
elif s in ('c', 'd'):
return 2
else:
return 3


Related Topics



Leave a reply



Submit