How to Sort Array in Ruby?

Ruby has built-in methods to sort given array.

  • sort
  • sort_by
  • sort!

Syntax:

Array.sort -> new_array

This sort will retruns new Array

similarly sort! will also sort the array, instead of creating new array it will modify the existing array

Example

# Array with initail values

numbers = [5,3,2,1]

# sort numbers array and return new array with sorted elements.

numbers.sort

Output

=> [1, 2, 3, 5]

 

with sort!

# Array with initail values

numbers = [5,3,2,1]

# sort numbers array and return new array with sorted elements.

numbers.sort!

 

Output

=> [1, 2, 3, 5]

 

Customized Sorting With sort_by

Examples

Sort by length

strings = %w(foo test blog a)

strings.sort_by(&:length)

 

Output

=> ["a", "foo", "test", "blog"]

 

Example 2:

table = ["Kiran","Powel","Polard","Lara","Shreya","Shakeela"]

puts "Array sort implementation"

new_arr = table.sort{|a,b| b<=>a}

puts "Array after sorting: #{new_arr}"

puts "Original Array instance: #{table}"

 

Output

Array sort implementation
Array after sorting: ["Shreya", "Shakeela", "Powel", "Polard", "Lara", "Kiran"]
Original Array instance: ["Kiran", "Powel", "Polard", "Lara", "Shreya", "Shakeela"]

 

Sort by Capital Words

Example 3:

text="Ruby is programming Language"

text

.split

.sort_by { |w| w[0].match?(/[A-Z]/) ? 0 : 1 }

.join(" ")

 

Output

=> "Ruby Language is programming"

 

Sort in Reverse Order

How to sort array revers order with length

Example:

strings = "Ruby is Programming language"

strings.split.sort { |a,b| a.length <=> b.length }

 

Output

=> ["is", "Ruby", "language", "Programming"]