Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

Wednesday, October 19, 2011

Ruby compact only compacts one level deep

My simple solution... recursively remove nil. Kinda lame but oh well.

  #
  # Recursively clean nils out of our array structures...
  #
  def arrayDeepCompact(array)
    array.each do |element|
      if element.kind_of?(Array)
        element.compact!
        arrayDeepCompact(element)
      end
    end
  end
Or if you prefer an extension
#
# Recursively clean nils out of our array structures...
#
class Array
 
  def deep_compact()
    dc(self)
  end
 
  private
 
  def dc(array)
    array.each do |element|
      if element.kind_of?(Array)
        element.compact! #compact first so won't need to itter over nil
        dc(element)
      end
    end
  end
 
end