How to Sort an Array of Ruby Objects by Property in Descending Order?

In Ruby, you can sort an array of objects by a specific property in the following ways:

  1. Using Array#sort_by;
  2. Using Array#sort.

Using Array#sort_by

You can use the Array#sort_by method in either of the following ways to sort an array by an object property in descending order:

  1. Block syntax:
    objects.sort_by { | obj | obj.property }.reverse
    
  2. "&:symbol" syntax:
    objects.sort_by(&:property).reverse
    

For example, consider the following array of objects of the "MyObject" class:

class MyObject
  attr_accessor :name

  def initialize(name)
    @name = name
  end
end

objects = [MyObject.new('B'), MyObject.new('A'), MyObject.new('C')]

You can sort the "objects" array in descending order using the "&:symbol" syntax in the following way:

# ...
sorted_objs = objects.sort_by(&:name).reverse

print sorted_objs
#=> [#<MyObject @name="C">, #<MyObject @name="B">, #<MyObject @name="A">]

Alternatively, you can use the block syntax to achieve the same, for example, like so:

# ...
sorted_objs = objects.sort_by { | obj | obj.name }.reverse

print sorted_objs
#=> [#<MyObject @name="C">, #<MyObject @name="B">, #<MyObject @name="A">]

To sort the array in ascending order by object property, you can simply remove the Array#reverse method that's called on the result of Array#sort_by.

Using Array#sort

You can use the Array#sort method with a block of code to sort an array by an object property in descending order:

objects.sort { | a, b | b.name <=> a.name }

Please note that the "<=>" symbol refers to the spaceship operator, which is a comparison operator often used for sorting and comparing objects.

For example, consider the following array of objects of the "MyObject" class:

class MyObject
  attr_accessor :name

  def initialize(name)
    @name = name
  end
end

objects = [MyObject.new('B'), MyObject.new('A'), MyObject.new('C')]

You can sort the "objects" array in descending order in the following way:

# ...
sorted_objs = objects.sort { | a, b | b.name <=> a.name }

print sorted_objs
#=> [#<MyObject @name="C">, #<MyObject @name="B">, #<MyObject @name="A">]

To sort the array in ascending order by object property, you can simply reverse the order of the arguments in the Array#sort method's block.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.