Codectionary / Developer documentation / Ruby

Sorting by Derived Keys

sort_by computes a sorting key for each item and returns a new sorted array. Array keys express multiple ordered criteria. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

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
  1. Expected output: ["fig", "pear", "plum", "apple"] ["pear", "fig", "plum", "apple"]
  2. 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

Specifications & further reading