Sorting an Array in Ruby

Sorting an array in Ruby is done with the help of sort method. This method allows you to sort homogenous array in the alphanumeric order depending on the type of the data in an array object.

my_array = [1,4,5,7,21,1,4,2]
my_array.sort

In addition to sorting by array values, you can sort by passing a parameter to sort function via sort_by

my_array = [[1],[1,2],[1,2,3]]
my_array.sort_by{|item|item.size} //Array will be sorted by the size of the arrays within.

Ruby allows you to sort an array of objects by one of the objects fields:

Class Car
  attr_reader :title, :speed, :hp

  def initialize(title, speed, ho)
   @title, @speed, @hp = title, speed, hp
  end

end

my_array = [Car.new(“BMW”,200,356), Car.new(“Tyota”,150,230)]
my_array.sort_by {|item| item.speed}

In addition, an Array sort_by method allows you to apply lowercase to an array object before sorting can be applied as in the following example.

my_array = [“Army”, “Zero”, “ship”, “car”]
my_array.sort_by{|item|item.downcase}

An Array class method sort_by employs a Schwartzian Transform technique. This approach makes sort_by method very efficient at sorting and faster due to the fact that it is implemented in C.

Alternatively, you can  use Hash in order to employ Schwartzian Transform technique. Example of this sorting is presented below.

m = {}
list.sort { |x,y| (m[x] ||= x.downcase) <=> (m[y] ||= y.downcase) }

You can employ shuffling of an array in order to achieve randomized sort with the help of rand function.

my_array.sort_by{rand}

Alternatively to rand you can use shuffle method of an Array class. Shuffle provides better performance when compared to sort_by{rand} approach.

You can also employ array for finding smallest to biggest item in an array. Array’s default sort always follow natural order of things: number are sorted by value and string are sorted by ASCII sequence.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…