rails array sort
# Step 1: Define an array of objects to be sorted
objects = [
{ name: 'John', age: 25 },
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 22 }
]
# Step 2: Use the `sort_by` method to sort the array based on a specific attribute
sorted_objects = objects.sort_by { |object| object[:age] }
# Step 3: Display the sorted array
puts sorted_objects
This code defines an array of objects, each having a name
and age
. It then uses the sort_by
method to sort the array based on the age
attribute in ascending order. Finally, the sorted array is displayed using puts
.