Ruby 中按对象属性的 Uniq [英] Uniq by object attribute in Ruby

查看:19
本文介绍了Ruby 中按对象属性的 Uniq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What's the most elegant way to select out objects in an array that are unique with respect to one or more attributes?

这些对象存储在 ActiveRecord 中,因此使用 AR 的方法也可以.

These objects are stored in ActiveRecord so using AR's methods would be fine too.

推荐答案

使用 Array#uniq 带块:

Use Array#uniq with a block:

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

这篇关于Ruby 中按对象属性的 Uniq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆