开发者社区 问答 正文

Ruby中的Uniq按对象属性

在数组中选择相对于一个或多个属性唯一的对象的最优雅方法是什么?

这些对象存储在ActiveRecord中,因此使用AR的方法也可以。 问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-07 23:02:40 1226 分享 版权
2 条回答
写回答
取消 提交回答
  • Array#uniq

    a = [ "a", "a", "b", "b", "c" ]
    a.uniq   # => ["a", "b", "c"]
    
    b = [["student","sam"], ["student","george"], ["teacher","matz"]]
    b.uniq {|s| s.first}   # => [["student", "sam"], ["teacher", "matz"]]
    
    2020-03-14 14:38:11
    赞同 展开评论
  • 使用Array#uniq带块:

    @photos = @photos.uniq { |p| p.album_id }

    2020-02-07 23:02:53
    赞同 展开评论
问答标签:
问答地址: