ruby - 在 Ruby 中对多维数组进行排序

标签 ruby arrays sorting multidimensional-array

我有一个数组:

[26] pry(#<HomeController>)> repos.class
=> Array
[27] pry(#<HomeController>)> repos.size
=> 2319
[28] pry(#<HomeController>)> 

关注列表,由不同类型的元素组成:

[29] pry(#<HomeController>)> repos[0]
=> #<Watchlist _id: 4f82c1127c0c220001000002, _type: nil, searchable_values: ["description:grit", "description:gives", "description:you", "description:object", "description:oriented", "description:read", "description:write", "description:access", "description:to", "description:git", "description:repositories", "description:via", "description:ruby", "tag:git", "html_url:https", "html_url:github", "html_url:com", "html_url:mojombo", "html_url:grit"], arrangeable_values: {"description"=>"Grit gives you object oriented read/write access to Git repositories via Ruby.", "tag"=>"git", "html_url"=>"https://github.com/mojombo/grit"}, html_url: "https://github.com/mojombo/grit", description: "Grit gives you object oriented read/write access to Git repositories via Ruby.", forks: 269, watchers: 1536, created_at: 2007-10-29 14:37:16 UTC, pushed_at: 2012-09-04 21:54:09 UTC, avatar_url: "https://secure.gravatar.com/avatar/25c7c18223fb42a4c6ae1c8db6f50f9b?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png", tags_array: ["git"], fork_: "false">

[30] pry(#<HomeController>)> repos[1]
=> #<Watchlist _id: 4f82c1127c0c220001000003, _type: nil, searchable_values: ["description:ruby", "description:process", "description:monitor", "html_url:https", "html_url:github", "html_url:com", "html_url:mojombo", "html_url:god"], arrangeable_values: {"description"=>"Ruby process monitor", "tag"=>"", "html_url"=>"https://github.com/mojombo/god"}, html_url: "https://github.com/mojombo/god", description: "Ruby process monitor", forks: 218, watchers: 1181, created_at: 2008-01-13 05:16:23 UTC, pushed_at: 2012-10-02 23:15:44 UTC, avatar_url: "https://secure.gravatar.com/avatar/25c7c18223fb42a4c6ae1c8db6f50f9b?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png", tags_array: [], fork_: "false">

如何使用名为 watchers 的监视列表字段对监视列表元素进行排序?

[31] pry(#<HomeController>)> repos[0].watchers
=> 1536
[29] pry(#<HomeController>)> repos[1].watchers
=> 1181
[32] pry(#<HomeController>)> 

最佳答案

repos.sort_by(&:watchers)

返回排序后的数组。要就地排序,请改用 sort_by!

如果一个元素可能没有 watchers 方法,您可以试试这个:

repos.sort_by { |e| e.watchers rescue 0 }

如果它们不都是整数,你可以转换它们:

repos.sort_by { |e| e.watchers.to_i }

关于ruby - 在 Ruby 中对多维数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13637341/

相关文章:

mysql - 更新 Rails 关联表

PHP MYSQL : Printing 2D arrays

arrays - 将函数传递给数组过滤器函数错误 - Swift 4

sql - 使 Oracle 排序不区分大小写?

javascript - 按重要性对数组进行排序

ruby : return from calling method

ruby - "shadowing"在 Ruby 中是什么意思?

Javascript:如何获取数组中特定顺序的值的索引?

python - 从列表中删除重复项并按相反顺序排序的最佳/最pythonic方法

ruby-on-rails - Heroku Slug 大小为 237MB, repo 大小为 70MB