Ruby: check if all array elements are equal
You could also use .uniq
, that returns an array with no duplicates, and check the size:
def all_equal?(arr)
arr.uniq.size <= 1
end
Couple of ways.
The best one:
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's a sortable array, then:
array.min == array.max
And, just for sake of variety:
!array.any?{ |element| element != array[0] } # or array.first instead of array[0]
Alternatively:
array.all?{ |element| element == array[0] } # or array.first instead of array[0]
Using Enumerable#each_cons:
def all_equal?(xs)
xs.each_cons(2).all? { |x, y| x == y }
end