Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Ruby Array of Clothing Sizes

Tags:

sorting

ruby

Given the following ruby array:

["2XL", "3XL", "4XL", "5XL", "6XL", "L", "M", "S", "XL"]

How do I sort it so that it is in this order?

["S", "M", "L", "XL", "2XL", "3XL", "4XL", "5XL", "6XL"]

Note that every size is not always present.

For history's sake, this was my original implementation.

sorted_sizes = []

sorted_sizes << "S" if sizes.include?("S")
sorted_sizes << "M" if sizes.include?("M")
sorted_sizes << "L" if sizes.include?("L")
sorted_sizes << "XL" if sizes.include?("XL")
sorted_sizes << "2XL" if sizes.include?("2XL")
sorted_sizes << "3XL" if sizes.include?("3XL")
sorted_sizes << "4XL" if sizes.include?("4XL")
sorted_sizes << "5XL" if sizes.include?("5XL")
sorted_sizes << "6XL" if sizes.include?("6XL")

sorted_sizes
like image 308
silasjmatson Avatar asked Oct 18 '13 22:10

silasjmatson


People also ask

How do you sort an array of objects in Ruby?

The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.

How do you sort an array of strings in Ruby?

In Ruby, it is easy to sort an array with the sort() function. When called on an array, the sort() function returns a new array that is the sorted version of the original one.

How do you arrange an array in ascending order Ruby?

#1: Using the sort method The sort method is defined in the Enumerable module, and it returns the values of the array sorted. By default, the method will return the items in the array sorted in ascending order.


1 Answers

["S", "M", "L", "XL", "2XL", "3XL", "4XL", "5XL", "6XL"] & ["2XL", "3XL", "4XL", "5XL", "6XL", "L", "M", "S", "XL"]
# => ["S", "M", "L", "XL", "2XL", "3XL", "4XL", "5XL", "6XL"]
like image 191
sawa Avatar answered Oct 19 '22 05:10

sawa