Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a variable against two different values in Ruby

Tags:

ruby

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?

like image 302
vonconrad Avatar asked Jan 14 '10 03:01

vonconrad


People also ask

How do you compare two variables in Ruby?

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.)

How do you compare numbers in Ruby?

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.

Can a method return two values Ruby?

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.

How do you check greater than in Ruby?

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.


1 Answers

Put all values into an array and then it should be easy.

%w[foo bar].include?('foo') # => true

[3,5].include?(3) # => true
like image 194
bryantsai Avatar answered Sep 30 '22 17:09

bryantsai