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.