Naturally

Gem Version Build Status Code Climate

Natural (version number) sorting with added support for legal document numbering. See Sorting for Humans : Natural Sort Order and Counting to 10 in Californian for the motivations to make this library. This is also the kind of ordering you want if you're sorting version numbers.

The core of the search is from here. I then made several changes to handle the particular types of numbers that come up in statutes, such as 335.1, 336, 336a, etc.

Naturally will also sort "numbers" in college course code format such as MATH101, MATH102, .... See the specs for examples.

Installation

Add this line to your application's Gemfile:

gem 'naturally'

And then execute:

$ bundle

Or install it outside of bundler with:

$ gem install naturally

Usage

require 'naturally'

# Sort a simple array of strings
Naturally.sort(["1.1", "1.10", "1.2"])  # => ["1.1", "1.2", "1.10"]

Usually, however, the library is used to sort an array of some kind of object:

  describe '#sort_naturally_by' do
    it 'sorts by an attribute' do
      UbuntuVersion = Struct.new(:name, :version)
      releases = [
        UbuntuVersion.new('Saucy Salamander', '13.10'),
        UbuntuVersion.new('Raring Ringtail',  '13.04'),
        UbuntuVersion.new('Precise Pangolin', '12.04.4'),
        UbuntuVersion.new('Maverick Meerkat', '10.10'),
        UbuntuVersion.new('Quantal Quetzal',  '12.10'),
        UbuntuVersion.new('Lucid Lynx',       '10.04.4')
      ]
      sorted = Naturally.sort_by(releases, :version)
      expect(sorted.map(&:name)).to eq [
        'Lucid Lynx',
        'Maverick Meerkat',
        'Precise Pangolin',
        'Quantal Quetzal',
        'Raring Ringtail',
        'Saucy Salamander'
      ]
    end
  end

See the spec for more examples.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request