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