如何使用 ruby 中的 sort_by 按字母顺序对数组进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11531061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you sort an array alphabetically using sort_by in ruby?
提问by Brian Weinreich
I have an array of memberships. In each membership is a group. I need to sort this array of memberships by the name of the group. I've tried a bunch of different ways, and the latest way is this:
我有一系列的会员资格。在每个成员中是一个组。我需要按组的名称对这个成员资格数组进行排序。我尝试了很多不同的方法,最新的方法是这样的:
@memberships.sort_by! { |m| m.group.name }
However, this doesn't sort by the name. It appears to be randomly sorting the array.
但是,这不按名称排序。它似乎是随机排序数组。
- Membership belongs_to :group
- Group has_many :memberships
- 成员属于_to :group
- 组 has_many :memberships
@memberships is equal to:
@memberships 等于:
[
{
id: 2141,
user_id: 491,
group_id: 271,
member_type: "member",
group: {
id: 271,
name: "Derek's",
privacy: "open",
bio_image_url: "/bio_images/medium/missing.png?1340285189",
member_count: 1,
upcoming_checkins_count: 0
}
},
{
id: 2201,
user_id: 221,
group_id: 291,
member_type: "member",
group: {
id: 291,
name: "Rounded Developement",
privacy: "closed",
bio_image_url: "/groups/medium/291/bioimage.jpg?1340736175",
member_count: 7,
upcoming_checkins_count: 0
}
}
]
NOTE: This does work --> @memberships.sort_by! { |m| m.group.id }
注意:这确实有效 --> @memberships.sort_by!{ |米| m.group.id }
It will order the array based on the group.id so maybe it has something to do with sorting alphabetically?
它会根据 group.id 对数组进行排序,所以也许它与按字母顺序排序有关?
Any help would be much appreciated.
任何帮助将非常感激。
回答by Brian Weinreich
Wow, after struggling with this for an extremely long time, I realized my problem was a simple one. I was sorting by group.name but some of the group names were uppercase and some were lower, which was throwing it all off. Converting everything to downcase worked well.
哇,在为此挣扎了很长时间后,我意识到我的问题很简单。我是按 group.name 排序的,但有些组名是大写的,有些是小写的,这一切都被抛弃了。将所有内容转换为小写效果很好。
@memberships.sort_by!{ |m| m.group.name.downcase }
回答by Angelo
Is the sort method an option?
排序方法是一种选择吗?
ary.sort{ |a,b| a[:group][:name] <=> b[:group][:name] }
回答by Dty
I don't see how your code is working. I can't access the hashes in the arrays using m.group.name
我不明白你的代码是如何工作的。我无法访问数组中的哈希使用m.group.name
Here's a working syntax
这是一个有效的语法
@memberships.sort_by!{ |m| m[:group][:name] }

