This is more a question of semantics than anything else.
I'd like to check if a variable is either one of two values. The easiest way of doing this would be:
if var == "foo" || var == "bar"
# or
if var == 3 || var == 5
But this doesn't feel very DRY to me. I know I can use String.match()
, but that doesn't work for non-string variables and is three times slower.
Is there a better way of checking a variable against two values?
You cannot compare variables, you can only compare objects, and variables aren't objects. Ruby doesn't have a case statement, only a case expression. (In fact, Ruby doesn't have statements at all.)
In order to compare things Ruby has a bunch of comparison operators. The operator == returns true if both objects can be considered the same. For example 1 == 1 * 1 will return true , because the numbers on both sides represent the same value.
The rule for methods is that they can only return one value. That is one object. So if we want to return more than one value, then we need to take whatever values we have and put them in some kind of a Ruby object that can hold more than one value. Typically that means an array or a hash.
Greater Than(>) operator checks whether the first operand is greater than the second operand. If so, it returns true. Otherwise it returns false. For example, 6>5 will return true.
Put all values into an array and then it should be easy.
%w[foo bar].include?('foo') # => true
[3,5].include?(3) # => true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With