The project is in a healthy, maintained state
Natural sort for strings containing numbers. Splits strings into text and numeric chunks and compares them the way humans expect: "file2" sorts before "file10".
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies
 Project Readme

philiprehberger-natural_sort

Tests Gem Version Last updated

Human-friendly natural sorting — "file2" before "file10"

Requirements

  • Ruby >= 3.1

Installation

Add to your Gemfile:

gem "philiprehberger-natural_sort"

Or install directly:

gem install philiprehberger-natural_sort

Usage

require "philiprehberger/natural_sort"

sorted = Philiprehberger::NaturalSort.sort(["file10", "file2", "file1"])
# => ["file1", "file2", "file10"]

Sorting with a Block

items = [{ name: "img10" }, { name: "img2" }, { name: "img1" }]
sorted = Philiprehberger::NaturalSort.sort_by(items) { |x| x[:name] }
# => [{ name: "img1" }, { name: "img2" }, { name: "img10" }]

Comparing Two Strings

Philiprehberger::NaturalSort.compare("file2", "file10")
# => -1

Philiprehberger::NaturalSort.compare("file10", "file2")
# => 1

Using a Comparator Proc

cmp = Philiprehberger::NaturalSort.comparator
["file10", "file2", "file1"].sort(&cmp)
# => ["file1", "file2", "file10"]

Case-Sensitive Mode

Philiprehberger::NaturalSort.sort(["Banana", "apple"], case_sensitive: true)
# => ["Banana", "apple"]

API

Method Description
NaturalSort.sort(array, case_sensitive: false) Sort an array of strings in natural order
NaturalSort.sort_by(array, case_sensitive: false) { |x| ... } Sort by block result in natural order
NaturalSort.compare(a, b, case_sensitive: false) Compare two strings, returns -1, 0, or 1
NaturalSort.comparator(case_sensitive: false) Returns a reusable comparison Proc

Development

bundle install
bundle exec rspec
bundle exec rubocop

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT