1

I'm using RoR 5. How do I select unique attribute values from an array of objects? I've tried

attr_values = my_objects.uniq{|r| r.attr_name}

But "attr_values" is an array of objects of the same type that "my_objects" consists of. I want the array to be objects of the type of "r.attr_name."

6
  • Can you give an example of the input and expected output? If this is a collection of records from the database you can use .distinct or grouping instead which avoids loading a huge amount of records from the DB. Commented Oct 5, 2017 at 14:29
  • How about my_objects.pluck(:attr_name).uniq Commented Oct 5, 2017 at 14:30
  • @bkunzi01 using my_objects.pluck('DISTINCT attr_name') could be better than pulling all the data out in the first place. Commented Oct 5, 2017 at 14:32
  • 1
    I'm guessing attr_values = my_objects.map(&:attr_name).uniq is what he is looking for but its a really fuzzy question. @SergioTulentsev Commented Oct 5, 2017 at 14:37
  • 1
    Read the comments too late, but @max has it right. You can combine .distinct and .pluck without the SQL segment, see my answer. @bkunzi01, your solution creates a big array, only to remove duplicates later, it won't be performant. Commented Oct 5, 2017 at 16:18

1 Answer 1

2

It's not clear on your post, but if that "array" is instead an ActiveRecord::Relation, you could do .distinct.pluck(:attr_name), for example: User.distinct.pluck(:role) => SELECT DISTINCT "users"."role" FROM "users"

If it's actually an array (my_objects.is_a? Array), the solution is my_objects.map(&:attr_name).uniq.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.