如何以更简洁的方式构建此方法?
how can I build this method in a more concise way?
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
我想用更concise/stylish的方式来写这个方法
排序方式说明:
#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
排序。
I'm using pure ruby but including Active Support
至于简洁和风格,你的代码看起来还不错。它组织良好且可读性强。
我确实看到了一种优化性能的方法:如果我对方法的理解正确,那么如果你有平局(即两个项目都是比较是相同的:"F" vs "F")。因此,只要 2 项不同,您就可以尽早 return:
_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
return side_one <=> side_two if a != b
end
我唯一的其他建议是注意方法是否太长。这个超过 20 行,您应该考虑将一些逻辑分离到一个单独的方法中。也许是这样的:
_sort_items.each do |sort_item|
a = first_item.send(sort_item.item_name)
b = second_item.send(sort_item.item_name)
add_to_sides(a, b, side_one, side_two)
return side_one <=> side_two if a != b
end
.
.
.
def add_to_sides(a, b, side_one, side_two)
.
.
.
end
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
我想用更concise/stylish的方式来写这个方法
排序方式说明:
#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
排序。
I'm using pure ruby but including Active Support
至于简洁和风格,你的代码看起来还不错。它组织良好且可读性强。
我确实看到了一种优化性能的方法:如果我对方法的理解正确,那么如果你有平局(即两个项目都是比较是相同的:"F" vs "F")。因此,只要 2 项不同,您就可以尽早 return:
_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
return side_one <=> side_two if a != b
end
我唯一的其他建议是注意方法是否太长。这个超过 20 行,您应该考虑将一些逻辑分离到一个单独的方法中。也许是这样的:
_sort_items.each do |sort_item|
a = first_item.send(sort_item.item_name)
b = second_item.send(sort_item.item_name)
add_to_sides(a, b, side_one, side_two)
return side_one <=> side_two if a != b
end
.
.
.
def add_to_sides(a, b, side_one, side_two)
.
.
.
end