require 'set' s = [1, 2, 3, -1, -2, -4].to_set # Divide the set into sets of adjacent numbers p s.divide { |x,y| (x-y).abs == 1 } # => #<Set: {#<Set: {1, 2, 3}>, # => #<Set: {-1}>, # => #<Set: {-4, -3}>}>