Given the following ruby array:
鉴于以下ruby数组:
["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
4 个解决方案
#1
15
["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"]
#2
6
Here's a way to do it that can handle repeats:
这是一种可以处理重复的方法:
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) }
#3
4
I really like @nicooga's version to this problem and would just suggest to wrap the logic in a lambda. That way it can be used in many places throughout the code.
我非常喜欢@ nicooga的版本来解决这个问题,并且建议将逻辑包装在lambda中。这样,它可以在整个代码中的许多地方使用。
clothing_size = ->x{%w(S M L 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
1
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
15
["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"]
#2
6
Here's a way to do it that can handle repeats:
这是一种可以处理重复的方法:
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) }
#3
4
I really like @nicooga's version to this problem and would just suggest to wrap the logic in a lambda. That way it can be used in many places throughout the code.
我非常喜欢@ nicooga的版本来解决这个问题,并且建议将逻辑包装在lambda中。这样,它可以在整个代码中的许多地方使用。
clothing_size = ->x{%w(S M L 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
1
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"]