0.06
No commit activity in last 3 years
No release in over 3 years
Natural sorting support for Ruby
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies
 Project Readme

Natural Sort

Build Status Gem Version Code Climate

Natual sorting implementation in Ruby.

Installation

Add this line to your application's Gemfile:

gem "natural_sort"

And then execute:

$ bundle

Or install it yourself as:

$ gem install natural_sort

Usage

list = ["a10", "a", "a20", "a1b", "a1a", "a2", "a0", "a1"]
list.sort(&NaturalSort) # => ["a", "a0", "a1", "a1a", "a1b", "a2", "a10", "a20"]
list = ["a10", "a", "a20", "a1b", "a1a", "a2", "a0", "a1"]
NaturalSort.sort(list)  # => ["a", "a0", "a1", "a1a", "a1b", "a2", "a10", "a20"]
list = ["a10", "a", "a20", "a1b", "a1a", "a2", "a0", "a1"]
NaturalSort.sort! list  # => ["a", "a0", "a1", "a1a", "a1b", "a2", "a10", "a20"]
list  # => ["a", "a0", "a1", "a1a", "a1b", "a2", "a10", "a20"]
UbuntuRelease = Struct.new(:number, :name)

ubuntu_releases = [
  UbuntuRelease.new("9.04", "Jaunty Jackalope"),
  UbuntuRelease.new("10.10", "Maverick Meerkat"),
  UbuntuRelease.new("8.10", "Intrepid Ibex"),
  UbuntuRelease.new("10.04.4", "Lucid Lynx"),
  UbuntuRelease.new("9.10", "Karmic Koala"),
]

ubuntu_releases.sort_by { |v| NaturalSort(v.number) }
# => [
#   UbuntuRelease.new("8.10", "Intrepid Ibex"),
#   UbuntuRelease.new("9.04", "Jaunty Jackalope"),
#   UbuntuRelease.new("9.10", "Karmic Koala"),
#   UbuntuRelease.new("10.04.4", "Lucid Lynx"),
#   UbuntuRelease.new("10.10", "Maverick Meerkat")
# ]

Refinements

If you're running ruby 2.1 or newer, you can use refinements.

require "natural_sort/refinements"

class MyClass
  using NaturalSort

  list.natural_sort                         # => ["a", "a0", "a1", "a1a"...
  ubuntu_releases.natural_sort_by(&:number) # => [ UbuntuRelease.new("8.10"...
end

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/rwz/natural_sort.

License

The gem is available as open source under the terms of the MIT License.