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.

class Array
    def collapse_ranges
        return self if self.length <= 2
        self.uniq!
        self.sort! rescue nil
        temp_array, return_array = [], []
        self.each_with_index do |item, i|
            if item.respond_to?(:next)
                temp_array.push item
                if item.next != self[i + 1]
                    return_array.concat 3 <= temp_array.length ?
                        [temp_array.first..temp_array.last] :
                         temp_array
                    temp_array.clear
                end
            else
                return_array.concat 3 <= temp_array.length ?
                    [temp_array.first..temp_array.last] :
                     temp_array
                temp_array.clear
                return_array.push item
            end
        end
        return return_array
    end
end


>> [1, 3, 4, 5, 7, 8].collapse_ranges.join(', ')
=> 1, 3..5, 7, 8
>> %w(a c d e g i j).collapse_ranges.join(', ')
=> a, c..e, g, i, j
>> [1, 2.5, 3, 4, 5].collapse_ranges.join(', ')
=> 1, 2.5, 3..5
>> [1, 2, 3, 4, {:test => 'value'}, 5].collapse_ranges.join(', ')
=> 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.

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(', ')
=>

Array percentages of the maximum

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

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


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

class Array
    def percentages_of_maximum
        self.collect{ |i| ((i.to_f / self.sort.last.to_f) * 100).to_i }
    end
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.

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
  :gmail => lambda { |date|
    Time.now.beginning_of_day <= date ?
    "#{date.strftime('%I').to_i}:#{date.strftime('%M')} #{date.strftime('%p').downcase}" :
    Time.now.beginning_of_year <= date ?
    "#{date.strftime('%b')} #{date.day}" :
    "#{date.month}/#{date.day}/#{date.strftime('%y')}"
  }
)

ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
  :gmail => lambda { |date|
    Time.now.beginning_of_day <= date ?
    "#{date.strftime('%I').to_i}:#{date.strftime('%M')} #{date.strftime('%p').downcase}" :
    Time.now.beginning_of_year <= date ?
    "#{date.strftime('%b')} #{date.day}" :
    "#{date.month}/#{date.day}/#{date.strftime('%y')}"
  }
)


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.

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


And it works something like this:

>> (0.1).html_fraction
=> 0.1
>> (0.25).html_fraction
=> &frac14;
>> (0.50).html_fraction
=> &frac12;
>> (0.75).html_fraction
=> &frac34;
>> (1.0).html_fraction
=> 1.0
>> (2.25).html_fraction
=> 2&frac14;
>> (3.5).html_fraction
=> 3&frac12;
>> (4.75).html_fraction
=> 4&frac34;
>> (5.85).html_fraction
=> 5.85
>> (-1.5).html_fraction
=> -1&frac12;
>> (-1.6).html_fraction
=> -1.6;
>> (-0.25).html_fraction
=> -&frac14;
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS