Ruby’s array#uniq method will evaluate the values of an array, but also evaluate the internals of those values to determine uniqueness when passed a block.

>> arr = [{a: 1, b: 2, c: 3}, {a: 3, b: 5, c: 6}]
>> arr.uniq 
=> [{:a=>1, :b=>2, :c=>3}, {:a=>1, :b=>5, :c=>6}]
 
# But if we pass the block comparing object_ids
>> arr = [{a: 1, b: 2, c: 3}, {a: 1, b: 5, c: 6}]
>> arr.uniq {|obj| obj == obj.object_id}
=> [{:a=>1, :b=>2, :c=>3}]

As the documentation states, “If a block is given, it will use the return value of the block for comparison.”, so we can compare nested key/values object values in addition to entire array values.

Thanks to @SeanStavro for this one.

:)

Leave a Reply

Your email address will not be published. Required fields are marked *