Ruby: check if all elements of an array are equal

I'm having a problem with Ruby code. I want to check if all elements of an array are equal.

For example, let's say I have an array of 5s:

arr = [5, 5, 5, 5, 5]

      

I know I can do something like

arr[0] == arr[1] == arr[2] == arr[3] # == arr[4] == ...

      

but this is not possible for huge arrays, and also not very Ruby-like in my opinion. We can improve it by doing something like this:

def all_equal?(arr)
  for i in 0..(arr.size-2)
    if arr[i] != arr[i+1] then
      return false
    end
  end
  true
end

      

But I also think it's pretty ugly. So, is there a built-in / better / shorter (more Ruby-esque) way to do this?

TL; DR is the shortest / most Ruby-esque way to check if an array contains only one single element (for example [5, 5, 5]

) ?

Thank.

+3


source to share


4 answers


You can also use .uniq

that returns an array without duplicates and checks for size:



def all_equal?(arr)
    arr.uniq.size <= 1
end

      

+9


source


A couple of ways.

The best:

array.uniq.count <= 1 # or == 1 if it can't be an empty array

      

and

array == ([array.first] * array.count)

      

and

(array | array).count <= 1 # basically doing the same thing as uniq

      

also:



array.reduce(:|) == array.first # but not very safe

      

And if it is a sortable array, then:

array.min == array.max    

      

And just for the sake of variety:

!array.any?{ |element| element != array[0] } # or array.first instead of array[0]

      

As an alternative:

array.all?{ |element| element == array[0] } # or array.first instead of array[0]

      

+5


source


Sort the array and compare the first value with the last.

+2


source


Using Enumerable # each_cons , it stops at the first distinct value without intermediate sorting / uniq:

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

      

0


source







All Articles