DEV Community

loading...

Ruby - sort array of objects by attribute

cuonggt profile image Cuong Giang ・1 min read

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

Discussion (0)

pic
Editor guide