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

About this user

Duncan Beevers http://duncan.beevers.net

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Split String into roughly equal-sized chunks.

Split a string into an array of roughly equal sized chunks based on a string or regular expression delimiter.
Delimiter is preserved in output.

   1  
   2  class String
   3    def chunk_string(average_segment_size = 40, sclice_on = /\s+/)
   4      out = []
   5      slices_estimate = self.size.divmod(average_segment_size)
   6      slice_count = (slices_estimate[1] > 0 ? slices_estimate[0] + 1 : slices_estimate[0])
   7      slice_guess = self.size / slice_count
   8      previous_slice_location = 0
   9      (1..slice_count - 1).each do
  10        |i|
  11        slice_location = self.nearest_split(slice_guess * i, sclice_on)
  12        out << self.slice(previous_slice_location..slice_location)
  13        previous_slice_location = slice_location + 1
  14      end
  15      out << self.slice(previous_slice_location..self.size)
  16      out
  17    end
  18  
  19    def nearest_split(slice_start, slice_on)
  20      left_scan_location  = (self.slice(0..slice_start).rindex(slice_on)).to_i
  21      right_scan_location = (self.slice((slice_start+1)..self.size).index(slice_on)).to_i + slice_start
  22      ((slice_start - left_scan_location) < (right_scan_location - slice_start) ? left_scan_location : right_scan_location)
  23    end
  24  end

Return the extension from a file name

// Return the extension from a file name

   1  
   2  /(.*\.)(.*$)/.match(File.basename(file_name))[2]
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS