How do I test if all items in an array are identical?

RubyArrays

Ruby Problem Overview


I can generate a few lines of code that will do this but I'm wondering if there's a nice clean Rubyesque way of doing this. In case I haven't been clear, what I'm looking for is an array method that will return true if given (say) [3,3,3,3,3] or ["rabbits","rabbits","rabbits"] but will return false with [1,2,3,4,5] or ["rabbits","rabbits","hares"].

Thanks

Ruby Solutions


Solution 1 - Ruby

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 - Ruby

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 - Ruby

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 - Ruby

I used to use:

array.reduce { |x,y| x == y ? x : nil }

It may fail when array contains nil.

Solution 5 - Ruby

I would use:

array = ["rabbits","rabbits","hares", nil, nil]
array.uniq.compact.length == 1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbradView Question on Stackoverflow
Solution 1 - Rubysepp2kView Answer on Stackoverflow
Solution 2 - RubyFrancisco SotoView Answer on Stackoverflow
Solution 3 - RubyCary SwovelandView Answer on Stackoverflow
Solution 4 - RubyDepictureView Answer on Stackoverflow
Solution 5 - Rubyrony36View Answer on Stackoverflow