簡體   English   中英

在Ruby中對多維數組進行排序

[英]Sorting multidimensional array in Ruby

我有一個數組:

[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的 Watchlist字段對Watchlists元素進行排序?

[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 }

看起來你想要Array#sortby

repos.sort_by{|elem| elem.watchers }

它將按“觀察者”字段的值對數組進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM