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

Todd Sayre http://del.icio.us/sporkyy

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

Collapse ranges in arrays

Takes an Array and turns consecutive integers into Range objects.

   1  
   2  class Array
   3      def collapse_ranges
   4          return self if self.length <= 2
   5          self.uniq!
   6          self.sort! rescue nil
   7          temp_array, return_array = [], []
   8          self.each_with_index do |item, i|
   9              if item.respond_to?(:next)
  10                  temp_array.push item
  11                  if item.next != self[i + 1]
  12                      return_array.concat 3 <= temp_array.length ?
  13                          [temp_array.first..temp_array.last] :
  14                           temp_array
  15                      temp_array.clear
  16                  end
  17              else
  18                  return_array.concat 3 <= temp_array.length ?
  19                      [temp_array.first..temp_array.last] :
  20                       temp_array
  21                  temp_array.clear
  22                  return_array.push item
  23              end
  24          end
  25          return return_array
  26      end
  27  end


   1  
   2  >> [1, 3, 4, 5, 7, 8].collapse_ranges.join(', ')
   3  => 1, 3..5, 7, 8
   4  >> %w(a c d e g i j).collapse_ranges.join(', ')
   5  => a, c..e, g, i, j
   6  >> [1, 2.5, 3, 4, 5].collapse_ranges.join(', ')
   7  => 1, 2.5, 3..5
   8  >> [1, 2, 3, 4, {:test => 'value'}, 5].collapse_ranges.join(', ')
   9  => 1..4, testvalue, 5

Find missing array items

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.

   1  
   2  class Array
   3      def missing_items
   4          return [] if self.length <= 1
   5          self.uniq!
   6          self.sort! rescue nil
   7          begin
   8              (self.first..self.last).to_a - self
   9          rescue
  10              []
  11          end
  12      end
  13  end


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

Array percentages of the maximum

Returns an array whose elements are the percentage of each element compared to the maximum element in the array.

   1  >> [25, 150, 200, 5, 75, 125].percentages_of_maximum
   2  => [12, 75, 100, 2, 37, 62]


If you're using Rails, stick this in your "environment.rb" script in the "config" directory:

   1  class Array
   2      def percentages_of_maximum
   3          self.collect{ |i| ((i.to_f / self.sort.last.to_f) * 100).to_i }
   4      end
   5  end

Gmail Date Format Helper

I needed a short and intuitive way of showing dates, so rather than just making something up I decided to steal Google's short date format from Gmail. I'm sure they did usability studies and whatnot.

   1  ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
   2    :gmail => lambda { |date|
   3      Time.now.beginning_of_day <= date ?
   4      "#{date.strftime('%I').to_i}:#{date.strftime('%M')} #{date.strftime('%p').downcase}" :
   5      Time.now.beginning_of_year <= date ?
   6      "#{date.strftime('%b')} #{date.day}" :
   7      "#{date.month}/#{date.day}/#{date.strftime('%y')}"
   8    }
   9  )
  10  
  11  ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
  12    :gmail => lambda { |date|
  13      Time.now.beginning_of_day <= date ?
  14      "#{date.strftime('%I').to_i}:#{date.strftime('%M')} #{date.strftime('%p').downcase}" :
  15      Time.now.beginning_of_year <= date ?
  16      "#{date.strftime('%b')} #{date.day}" :
  17      "#{date.month}/#{date.day}/#{date.strftime('%y')}"
  18    }
  19  )


Put this code in your "environmen.rb" file in your "RAILS_ROOT/config" directory or make a new Ruby script file containing it in your "RAILS_ROOT/config/initializers" directory.

Float to HTML fraction entity

Uses HTML entities to display pretty fractional values for applicable floating point numbers.

   1  
   2  class Float
   3      def html_fraction
   4          self.to_s.
   5              sub(/(.+)\.0$/,     '\1'        ).  # Zero decimal
   6              sub(/(-?\d+)\.25$/, '\1&frac14;').  # One quarter
   7              sub(/(-?\d+)\.5$/,  '\1&frac12;').  # One half
   8              sub(/(-?\d+)\.75$/, '\1&frac34;').  # Three quarters
   9              sub(/^(-?)0(&.+)/,  '\1\2'      )   # Strip leading zeroes
  10      end
  11  end


And it works something like this:

   1  
   2  >> (0.1).html_fraction
   3  => 0.1
   4  >> (0.25).html_fraction
   5  => &frac14;
   6  >> (0.50).html_fraction
   7  => &frac12;
   8  >> (0.75).html_fraction
   9  => &frac34;
  10  >> (1.0).html_fraction
  11  => 1.0
  12  >> (2.25).html_fraction
  13  => 2&frac14;
  14  >> (3.5).html_fraction
  15  => 3&frac12;
  16  >> (4.75).html_fraction
  17  => 4&frac34;
  18  >> (5.85).html_fraction
  19  => 5.85
  20  >> (-1.5).html_fraction
  21  => -1&frac12;
  22  >> (-1.6).html_fraction
  23  => -1.6;
  24  >> (-0.25).html_fraction
  25  => -&frac14;
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS