12

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

5 Answers 5

24

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice. That would definitely be a better way than with the temp variables!
Note that you cannot use one? if they are to be nil or false.
5

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.

1 Comment

I like this solution as well, but without the module extension it is a bit more verbose than Shawn's answer.
3

How about:

[a,b,c,d] == [b,c,d,a]

Really just:

[a,b,c] == [b,c,d]

will do

Comments

2
a = [1,1,1]
(a & a).size == 1 #=> true

a = [1,1,2]
(a & a).size == 1 #=> false

3 Comments

shuffle is not valid, it could end up being in the same order.
@Pitri You know that [1,1,2].shuffle returns [1,1,2] sometimes, don't you? ;-)
Yes, you are right partially; so deleted. But shuffle does always,but when duplicate items will be present ,it would fail. :)
2
[b, c, d].all?(&a.method(:==))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.