如何在sort_by rails中找到基于某个属性的唯一记录

时间:2012-12-11 03:20:37

标签: ruby arrays

您好我有这些记录,我可以在sort_by方法块中找到唯一记录

   my array is like this

     [#<Post id: 1, name: "ali", team_elo: 0, team_name: "solo", created_at: 
     "2012-12-09  16:11:17", updated_at: "2012-12-11 03:39:43">,
     #<Post id: 2, name: "ramiz", team_elo: nil, team_name: "roko", created_at: 
     "2012-12-11 03:40:31", updated_at: "2012-12-11 03:40:31">,
     #<Post id: 3, name: "ramizrt", team_elo: nil, team_name: "joko", created_at: 
      "2012-12-11 03:40:47", updated_at: "2012-12-11 03:40:47">,
     #<Post id: 4, name: "lee", team_elo: nil, team_name: "roko", created_at: 
       "2012-12-11 03:41:15", updated_at: "2012-12-11 03:41:15">]

我如何在唯一的team_name基础上对这个数组进行排序。结果应该是这样的

       [#<Post id: 1, name: "ali", team_elo: 0, team_name: "solo", created_at: 
     "2012-12-09  16:11:17", updated_at: "2012-12-11 03:39:43">,
     #<Post id: 2, name: "ramiz", team_elo: nil, team_name: "roko", created_at: 
     "2012-12-11 03:40:31", updated_at: "2012-12-11 03:40:31">,
     #<Post id: 3, name: "ramizrt", team_elo: nil, team_name: "joko", created_at: 
      "2012-12-11 03:40:47", updated_at: "2012-12-11 03:40:47">]

由于

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

arr = arr.uniq { |x| x.team_name }

或其兄弟

arr.uniq! { |x| x.team_name }

arr仅设置为您想要的元素。