Over the past few days I have been picking up some Ruby. Overall, I enjoy the fully object oriented nature of the language. An interesting aspect of Ruby is its collections and the ability to create a heterogeneous or mixed set of objects. Although there are a number of debates on the usefulness of these types of collections, it is a good feature for those rare cases. One drawback of this feature is some methods such as .sort will produce an Error when applied to the mixed collection. One way to prevent this would be to detect if a collection was heterogeneous prior to the method call. After digging around, I found there was no clear way to detect this. So for any future padawan learner of Ruby I will share my solution.

# Detect for heterogeneous array
array = [1, 4, "hello", [2, 4], 3.5]
if array.map {|e| e.class}.uniq.size > 1
  puts "Heterogeneous Collection"

Using the map iterator, the code will generate a new array of object class definitions for every object in the collection. Now, it is a matter of checking for the number of uniques in the resulting array. If it is more than one, you will have yourself a mixed collection.