philiprehberger-natural_sort
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_sortUsage
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")
# => 1Using 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 rubocopSupport
If you find this project useful: