How to Sort an Array of Ruby Objects by Property in Ascending 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 ascending order:

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

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 ascending order using the "&:symbol" syntax in the following way:

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

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

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

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

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

To sort the array in descending order by object property, you can simply call the Array#reverse method 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 ascending order:

objects.sort { | a, b | a.name <=> b.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 ascending order in the following way:

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

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

To sort the array in descending 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.