How do I test if all items in an array are identical?
Solution 1:
You can use Enumerable#all?
which returns true if the given block returns true for all the elements in the collection.
array.all? {|x| x == array[0]}
(If the array is empty, the block is never called, so doing array[0]
is safe.)
Solution 2:
class Array
def same_values?
self.uniq.length == 1
end
end
[1, 1, 1, 1].same_values?
[1, 2, 3, 4].same_values?
What about this one? It returns false for an empty array though, you can change it to <= 1 and it will return true in that case. Depending on what you need.
Solution 3:
I too like preferred answer best, short and sweet. If all elements were from the same Enumerable class, such as Numeric or String, one could use
def all_equal?(array) array.max == array.min end
Solution 4:
I would use:
array = ["rabbits","rabbits","hares", nil, nil]
array.uniq.compact.length == 1
Solution 5:
I used to use:
array.reduce { |x,y| x == y ? x : nil }
It may fail when array
contains nil
.