Sorting helps organize data in a way that makes it easier to find or understand. sort_by lets you decide exactly how to sort things based on your own rules.
0
0
Sort_by for custom sorting in Ruby
Introduction
When you want to sort a list of names by their length instead of alphabetically.
When you have a list of people and want to sort them by their age.
When sorting a list of files by their size or date created.
When you want to sort objects by a specific property, like price or rating.
Syntax
Ruby
array.sort_by { |item| expression }The block inside { } tells Ruby what to use for sorting each item.
The original array is not changed; sort_by returns a new sorted array.
Examples
This sorts names by their length, shortest first.
Ruby
names = ["Bob", "Alice", "Eve"] sorted = names.sort_by { |name| name.length }
This sorts numbers in descending order by using the negative value.
Ruby
numbers = [5, 2, 9, 1] sorted = numbers.sort_by { |num| -num }
This sorts people by their age, youngest first.
Ruby
people = [{name: "Bob", age: 30}, {name: "Alice", age: 25}]
sorted = people.sort_by { |person| person[:age] }Sample Program
This program sorts a list of fruits by the length of their names and prints the sorted list.
Ruby
fruits = ["apple", "banana", "pear", "kiwi"] sorted_fruits = fruits.sort_by { |fruit| fruit.length } puts sorted_fruits
OutputSuccess
Important Notes
If two items have the same sorting value, their order stays the same as in the original list (stable sort).
Use sort_by when sorting by a single property or calculation for better speed than sort with a block.
Summary
sort_by sorts items based on a value you choose for each item.
It returns a new sorted array without changing the original.
Use it to sort by length, age, price, or any custom rule you want.