Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three-way comparison in ruby

Tags:

ruby

What's the most concise way to ensure three variables are all equal in ruby? For example

dog = 'animal'
cat = 'animal'
chicken = 'animal'
shoe = 'clothing'

# Something like this...which doesn't work
dog == cat == chicken # true   
dog == cat == shoe # false
like image 406
PlankTon Avatar asked Oct 11 '12 18:10

PlankTon


2 Answers

The most concise way for three elements is (sorry to disappoint you):

dog == cat && cat == chicken

Of course you can always get clever if you want to...

[dog, cat, chicken] == [dog] * 3
[dog, cat, chicken].uniq.length == 1

...but that doesn't really make the code more concise (or readable).

I would do something like this if you want a reusable function that can compare arbitrarily many elements for equality:

def all_equal?(*elements)
  elements.all? { |x| x == elements.first }
end
like image 55
Dan Tao Avatar answered Oct 23 '22 11:10

Dan Tao


dog == cat && dog == chicken
like image 36
Dave Newton Avatar answered Oct 23 '22 12:10

Dave Newton