elder south
elder south

Reputation: 463

What is the proper syntax for multiple comparisons?

Is there a proper syntax in Ruby for comparing multiple values against the same variable? For example:

#!/usr/bin/ruby -w

y = 15
p 'success' if y == 1 || y == 5 || y == -2 || y == 15132 || y == 3.14159265  || y == 15

Can that be written as something along the lines of:

y = 15
p 'success' if y == 1,5,-2,15132,3.14159265,15

And, if so, would that also apply to while loops?

y = 15
while y != 1,5,-2,15132,3.14159265,15
y = rand(50)
p y
end

Based on my search I'm tending to believe this is either not possible, or it's too obscure for my searches.

I hope it's the second case.

I have already considered an array itteration solution, but it's not as pretty or simple as I'd like.

Upvotes: 1

Views: 930

Answers (5)

azgult
azgult

Reputation: 540

For a more general case you can use the any? method with a comparison block; this has the advantage of being usable with operators apart from ==:

p 'success' if [1, 5, -2, 15132, 3.14159265, 15].any? { |i| i == y }

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118271

From the Array#index :

Returns the index of the first object in ary such that the object is == to obj.Returns nil if no match is found.

p 'success' if [1,5,-2,15132,3.14159265,15].index(y)

Upvotes: 0

sawa
sawa

Reputation: 168131

case y
when 1, 5, -2, 15132, 3.14159265, 15 then p "success"
end

Upvotes: 3

PinnyM
PinnyM

Reputation: 35531

p 'success' if [1, 5, -2, 15132, 3.14159265, 15].include? y

Upvotes: 3

Jean-Bernard Pellerin
Jean-Bernard Pellerin

Reputation: 12670

You're looking for include?

p 'success' if [1,5,-2,15132,3.14159265,15].include? y

Upvotes: 3

Related Questions