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
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.
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.
#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.
["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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With