Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Find missing array items (See related posts)

This works fine for integers and letters. It should work for anything though, so long as Ruby can form an range from the first and last array items.

class Array
    def missing_items
        return [] if self.length <= 1
        self.uniq!
        self.sort! rescue nil
        begin
            (self.first..self.last).to_a - self
        rescue
            []
        end
    end
end


>> [1, 3, 4, 10].missing_items.join(', ')
=> 2, 5, 6, 7, 8, 9
>> [1, 2, 7, 7.5, 8.2].missing_items.join(', ')
=> 3, 4, 5, 6, 8
>> %w(a b c f g j).missing_items.join(', ')
=> d, e, h, i
>> [2.5, {:test => 'value'}].missing_items.join(', ')
=>

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts