Sortsmith is a flexible sorting library for Ruby that makes complex sorting operations simple and composable. It makes handling common sorting patterns like case-insensitive sorting of hashes and objects easy, while remaining extensible for custom sorting needs.
- Builder pattern for chainable sorting configuration
- Built-in support for case-insensitive sorting
- Hash key and method/attribute sorting
- Flexible transformation pipeline
Add this line to your application's Gemfile:
gem "sortsmith"
And then execute:
$ bundle install
Or install it yourself as:
$ gem install sortsmith
# Sort an array of Strings
users = ["Bob", "Alice", "Carol"]
sorted_users = Sortsmith::Sorter.new(users).sort
# Result: ["Alice", "Bob", "Carol"]
# Sort an array of hashes by a key
users = [
{ name: "Carol", age: 35 },
{ name: "Bob", age: 25 },
{ name: "Alice", age: 30 }
]
sorted_users = Sortsmith::Sorter.new(users)
.by_key(:name)
.sort
# Result: [{ name: "Alice" }, { name: "Bob" }, { name: "Carol" }]
# Sort objects by method/attribute
class User < Data.define(:name)
end
users = [User.new(name: "Bob"), User.new(name: "Carol"), User.new(name: "Alice")]
sorted_users = Sortsmith::Sorter.new(users)
.by_method(:name)
.sort
# Result: [#<data User name="Alice">, #<data User name="Bob">, #<data User name="Carol">]
users = [
{"name" => "bob"},
{"name" => "Billy"},
{"name" => "Alice"},
{"name" => "carol"},
{"name" => "Cassidy"},
{"name" => "alex"}
]
# Order of methods does not matter
# However, the hash's key type does
sorted_users = Sortsmith::Sorter.new(users)
.case_insensitive
.by_key("name")
.sort
# Result: [{"name"=>"Alice"}, {"name"=>"alex"}, {"name"=>"Billy"}, {"name"=>"bob"}, {"name"=>"Cassidy"}, {"name"=>"carol"}]
# Sort in descending order
sorted_desc = Sortsmith::Sorter.new(array)
.by_attribute(:name)
.desc
.sort
- Ruby 3.3.6
- Nix with Direnv (optional, but recommended)
With Nix:
direnv allow
Without Nix:
bundle install
bundle exec rake test
bundle exec steep check
This project uses StandardRB. To check your code:
bundle exec standardrb
To automatically fix issues:
bundle exec standardrb --fix
- Fork it
- Create your feature branch (
git checkout -b feature/my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin feature/my-new-feature
) - Create new Pull Request
Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.
The gem is available as open source under the terms of the MIT License.
See CHANGELOG.md for a list of changes.
- Author: Bryan "itsthedevman"