Check if a variable is equal to one of two values

I want to check if a 1 or 2

I could do

 a == 1 || a == 2 

but this requires repeating a (which would be annoying for longer variables)

I would like to do something like a == (1 || 2) , but obviously this will not work

I could do [1, 2].include?(a) which is nice, but it seems a little harder to read

Just wondering how to deal with this idiomatic ruby.

+48
ruby
Feb 03 '10 at 23:53 on
source share
7 answers

Your first method is idiomatic Ruby. Unfortunately, Ruby does not have the Python a in [1,2] equivalent, which I think would be nicer. Your [1,2].include? a [1,2].include? a is the closest alternative, and I think it is a little back from the most natural way.

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

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

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

+34
03 Feb 2018-10-03T00
source share

I don't know in what context you are using this, but if it fits into the switch statement, you can do:

 a = 1 case a when 1, 2 puts a end 

Some other advantages are that when using the equality operator case ===, so if you want, you can override this method for other behavior. Another thing is that you can also use ranges with it if this matches your use case:

 when 1..5, 7, 10 
+10
Feb 04 '10 at 1:10
source share

One way is to apply for "Matz" to add this functionality to the Ruby specification.

 if input == ("quit","exit","close","cancel") then #quit the program end 

But the case-when statement already does it this way:

 case input when "quit","exit","close","cancel" then #quit the program end 

When writing on one line like this, it acts and almost looks like an if statement. Is the bottom example a good temporary replacement for the top example? You will be the judge.

+7
Aug 30 '10 at 4:40
source share

First put it somewhere:

 class Either < Array def ==(other) self.include? other end end def either(*these) Either[*these] end 

Then then:

 if (either 1, 2) == a puts "(i'm just having fun)" end 
+5
Feb 04 '10 at 0:07
source share
 a.to_s()=~/^(1|2)$/ 
+4
Feb 04 '10 at 1:40
source share

You can just use an intersection, for example

 ([a] & [1,2]).present? 

alternative way.

+3
03 Feb '16 at 6:57
source share

Maybe I'm fat here, but it seems to me that

 (1..2) === a 

... works.

0
Feb 04 '10 at
source share



All Articles