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

Viewed 25091

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

5 Answers

I would use:

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