develop with

Unique list with records

When you need to have a uniq array with a given set of records

Most of you probably know about how to create a unique list of values with an array using the array.uniq in ruby. But did you know that you can pass in a block to uniq? This makes it extremely convenient for getting a unique set of objects based on a given field value.

For instance, here is an example of a unique array with id as the qualifier.

model_arr = []
model_arr << Model.new(id: 1)
model_arr << Model.new(id: 2)
model_arr << Model.new(id: 1)
model_arr.uniq { |model| model.id }

The returned value in the block is what the array logic will use to clean up the duplicate values. The resulting array in the above example will be a length of 2.

For more details on the uniq method see Ruby Docs Array.

comments powered by Disqus

Want to see a topic covered? create a suggestion

Get more developer references and books in the developwith store.