Open In App

How to Sort an Array alphabetically in Ruby?

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Sorting an array alphabetically is a common operation in Ruby and can be done using different methods. Sorting an array alphabetically refers to arranging its elements in the order of their lexemes either increased or decreased depending on such order. We will consider some methods that can help us achieve this:

  • Using the sort method
  • Using the sort_by method

Approach 1: Using the sort method

This method arranges an array according to the default comparison operator <=> or by a user-defined block if given. By default, for strings, the comparison is performed lexicographically (alphabetically).

SYNTAX:

sorted_array = array.sort

Example:

Ruby
# Sample array of strings
fruits = ["apple", "banana", "orange", "kiwi"]

# Sorting alphabetically using sort
sorted_fruits= fruits.sort

# Printing sorted array
puts "Sorted fruits: #{sorted_fruits}"

Output
Sorted fruits: ["apple", "banana", "kiwi", "orange"]

Approach 2 : Using the sort_by method

This technique allows greater flexibility with regard to sorting based on the results of executing a code block. It facilitates sorting not just directly on the element but also on computed values.

SYNTAX:

sorted_array = array.sort_by { |element| block }

Example:

Ruby
# Sample array of strings
fruits = ["apple", "banana", "orange",  "kiwi"]

# Sorting alphabetically using sort_by
sorted_fruits = fruits.sort_by { |fruit| fruit }

# Printing sorted array
puts "Sorted fruits: #{sorted_fruits}"

Output
Sorted fruits: ["apple", "banana", "kiwi", "orange"]

CONCLUSION:

Sorting arrays alphabetically in Ruby can be achieved by using either sort or sort_by methods. The former is easier and suitable for basic sorting purposes while the latter is more flexible as it can easily work with computed values. Understanding these methods and their differences enables developers choose the most effective way to meet their goals in sorting.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads