Sorting a ruby ​​array of clothes

Given the following ruby ​​array:

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

How to sort it so that it is in that order?

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

Please note that each size is not always present .

For the story, 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 
+6
source share
4 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"] 
+15
source

Here is a way to do this that can handle repetitions:

 SORT_ORDER = ["S", "M", "L", "XL", "2XL", "3XL", "4XL", "5XL", "6XL"] ["2XL", "3XL", "4XL", "5XL", "6XL", "L", "M", "S", "XL"].sort_by { |x| SORT_ORDER.index(x) } 
+6
source

I really like the @nicooga version for this problem and will just suggest wrapping the logic in lambda. Thus, it can be used in many places in the code.

 clothing_size = ->x{%w(SML XL 2XL 3XL 4XL 5XL 6XL).index(x)} size_list = ["2XL", "3XL", "4XL", "5XL", "6XL", "L", "M", "S", "XL"] size_list.sort_by &clothing_size 
+4
source
 array = ["2XL", "3XL", "4XL", "6XL", "L", "M", "S", "XL"] sort_order = ["S", "M", "L", "XL", "2XL", "3XL", "4XL", "5XL", "6XL"] sort_order - (sort_order - array) # => ["S", "M", "L", "XL", "2XL", "3XL", "4XL", "6XL"] 
+1
source

Source: https://habr.com/ru/post/956292/


All Articles