[英]How to sort array by multiple attributes in ruby?
I have list of user profiles. 我有用户配置文件列表。 I need to sort the user profile based on following criteria as shown below:
我需要根据以下条件对用户配置文件进行排序,如下所示:
profile_claimed(boolean) -> profile_complete_status(integer) -> No_of_friends(integer)
code: 码:
user_profiles.sort { |x| [x.claim ? 0 : 1, x.complete_profile_status, x.no_of_friends] }
How to sort the user profile? 如何排序用户配置文件?
You could use sort_by
: 你可以使用
sort_by
:
user_profiles.sort_by do |x|
[(x.claim ? 0 : 1), x.complete_profile_status, x.no_of_friends]
end
Also it is worth noting that sort_by
is usually faster than sort
, because it caches the result of the comparison operation, which in this case is 另外值得注意的是
sort_by
通常比sort
更快,因为它缓存了比较操作的结果,在这种情况下是
(x.claim ? 0 : 1), x.complete_profile_status, x.no_of_friends
and does not recalculate the values for each comparison between two elements. 并且不会重新计算两个元素之间每次比较的值。
You need to use sort
method with block: 您需要对块使用
sort
方法:
ary.sort do |x,y|
if x > y
1
elsif x < y
-1
else
0
end
end
Just make sure to return +1
when x
follows y
, -1
when y
follows x
, or 0
when they are equal. 只要确保在
x
跟随y
时返回+1
,当y
跟随x
时返回-1
,或者当它们相等时返回0
。
http://ruby-doc.org/core-2.2.0/Array.html#method-i-sort http://ruby-doc.org/core-2.2.0/Array.html#method-i-sort
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.