Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to test if multiple variables have same value, ruby

Tags:

syntax

ruby

Is there a simple way of testing that several variables have the same value in ruby?

Something linke this:

if a == b == c == d #does not work
   #Do something because a, b, c and d have the same value
end

Of course it is possible to check each variable against a master to see if they are all true, but that is a bit more syntax and is not as clear.

if a == b && a == c && a == d #does work
    #we have now tested the same thing, but with more syntax.
end

Another reason why you would need something like this is if you actually do work on each variable before you test.

if array1.sort == array2.sort == array3.sort == array4.sort #does not work
    #This is very clear and does not introduce unnecessary variables
end
#VS
tempClutter = array1.sort
if tempClutter == array2.sort && tempClutter == array3.sort && tempClutter == array4.sort #works
   #this works, but introduces temporary variables that makes the code more unclear
end
like image 537
Automatico Avatar asked May 15 '13 05:05

Automatico


2 Answers

Throw them all into an array and see if there is only one unique item.

if [a,b,c,d].uniq.length == 1
  #I solve almost every problem by putting things into arrays
end

As sawa points out in the comments .one? fails if they are all false or nil.

like image 77
Shawn Balestracci Avatar answered Oct 05 '22 10:10

Shawn Balestracci


tokland suggested a very nice approach in his comment to a similar question:

module Enumerable
  def all_equal?
    each_cons(2).all? { |x, y| x == y }
  end
end

It's the cleanest way to express this I've seen so far.

like image 28
Stefan Avatar answered Oct 05 '22 10:10

Stefan