【发布时间】:2015-10-17 18:44:43
【问题描述】:
def self.sort(_sort_items, _collection)
return _collection unless _sort_items
_collection.sort! do |first_item, second_item|
side_one = []
side_two = []
_sort_items.each do |sort_item|
a = first_item.send(sort_item.item_name)
b = second_item.send(sort_item.item_name)
if sort_item.descending
side_one << b
side_two << a
else
side_one << a
side_two << b
end
end
side_one <=> side_two
end
end
我想用更简洁/时尚的方式来写这个方法
排序方法说明:
#sort 方法接受一个集合并按多个属性排序。
如果我有这样的@collection:
和@sort_items:
@sort_items.add_item(:gender, true)
@sort_items.add_item(:age, false)
如果我执行:
MyClass.sort(@sort_items, @collection)
我会得到:
同一个集合首先由gender desc 排序,然后由age asc 排序。
我使用的是纯 ruby,但包括 Active Support
【问题讨论】:
-
当你说
sort_item.descendant时,你的意思是说sort_item.descending吗? -
哦!是的,我的英语很差......
-
如果
arr是一个包含两个元素的数组,其元素是age(一个Fixnum)和gender(一个字符串),你可以先按性别降序排序,然后再按年龄升序排序(打破平局)如下:arr.sort_by { |a,g| [g,-a] }.reverse. -
...或
arr.sort_by { |a,g| [(g=='M') ? 'F' : 'M', a] }。 -
在我的情况下,
arr可以包含两个或多个项目
标签: ruby coding-style activesupport