Syntax
items.sort_by { |item| [primary_key, secondary_key] }Examples
Sorting by Derived Keys
Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.
words = %w[pear fig plum apple]
sorted = words.sort_by { |word| [word.length, word] }
p sorted
p words- Expected output: ["fig", "pear", "plum", "apple"] ["pear", "fig", "plum", "apple"]
- Length is compared first, and alphabetical order breaks equal-length ties. The source array is unchanged.
Best practices
- Provide tie-breaker keys when reproducible ordering matters.
- Use sort_by! only when mutating the original array is intended.
Runtime & versions
Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Ruby documentation