Ruby has built-in methods to sort given array. 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 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"]
Array sort implementation
Array after sorting: ["Shreya", "Shakeela", "Powel", "Polard", "Lara", "Kiran"]
Original Array instance: ["Kiran", "Powel", "Polard", "Lara", "Shreya", "Shakeela"]
What are the various Ruby runtimes, and how are they different?
Program to Print Triangle of Numbers in Ruby
What are some of your favorite gems? What are their alternatives?
Ruby program to check whether the given number is palindrome
Ruby program to Calculate the factorial of given number
How to add/remove elements to Array in Ruby?
Ruby program to print an array
Ruby program to add two integer numbers
Ruby program to check whether the given number is prime or not
Ruby program to check whether the given number is Armstrong
How to Get Input with Gets in Ruby
How to shuffle an array in Ruby?
How to get index of array element in Ruby
How to Sort Array in Ruby?
How to Replace array elements in Ruby?
What are #method_missing and #send? Why are they useful?
how to create an array with Array.[](*args) in Ruby ?
Ruby program to print Fibonacci series
What's the difference between a lambda, a block and a proc?
Ruby program to reverse a string
Creating Array with Array.new(size, obj) in Ruby
How to create two dimensional array in ruby?
Ruby program to generate random numbers