DEV Community

Cuong Giang
Cuong Giang

Posted on

Ruby - sort array of objects by attribute

I have an array of subscriptions. Now I want to sort it by subscription's created_at and ascending order:

subscriptions.sort_by { |subscription| subscription.created_at }

A more concise approach:

subscriptions.sort_by(&:created_at)

To sort by descending order:

subscriptions.sort_by { |subscription| -subscription.created_at }

We also can use reverse method to reverse an array:

subscriptions.sort_by { |subscription| subscription.created_at }.reverse

# or

subscriptions.sort_by(&:created_at).reverse

Top comments (0)