def range_extract(l)
  
  
  sorted, range = l.sort.concat([Float::MAX]), []
  canidate_number = sorted.first

  
  sorted.each_cons(2) do |current_number, next_number|
    
    if current_number.succ < next_number
      
      if canidate_number == current_number
        
        range << canidate_number.to_s
      else
        
        
        seperator = canidate_number.succ == current_number? : 
        range <<  % [canidate_number, seperator, current_number]
      end
      
      canidate_number = next_number
    end
  end
  range.join(',')
end

lst = [
    0,  1,  2,  4,  6,  7,  8, 11, 12, 14,
   15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
   25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
   37, 38, 39
]

p rng = range_extract(lst)