Natual sorting implementation in Ruby.
Add this line to your application's Gemfile:
gem "natural_sort"
And then execute:
$ bundle
Or install it yourself as:
$ gem install natural_sort
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")
# ]
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
Bug reports and pull requests are welcome on GitHub at https://github.com/rwz/natural_sort.
The gem is available as open source under the terms of the MIT License.