5

I created a Ruby array (Articles) with an attribute (category) containing repeating preset values (e.g. one of the following: "Drink", "Main", "Side"). As result I'd like to get a list of all unique values of this category attribute.

I thought about something like

Article.all.category.uniq 

...but that didn't work. Here's an example array:

[#<Article id: 1, category: "Drink">, #<Article id: 2, category: "Main">, #<Article id: 3, category: "Drink">, #<Article id: 4, category: "Side">, #<Article id: 5, category: "Drink">, ] 

the content of the result list I am looking for should be in this case: "Drink", "Main", "Side"

Bernd
  • 11,133
  • 11
  • 65
  • 98

3 Answers3

17
Article.all.map {|a| a.category}.uniq

should do the job.

lucapette
  • 20,564
  • 6
  • 65
  • 59
  • 6
    +1. Or [the shorthand](http://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby): `Article.all.map(&:category).uniq`. – Alex Sep 19 '11 at 22:08
  • 1
    Yep. I tend to use the shorthand in my code because I like it. But it's a bit unclearer then the explicit version IMHO. – lucapette Sep 19 '11 at 22:14
  • 2
    Only do this if you want to kill your application. What you want is `Article.pluck(:category).uniq` – jurassic Sep 08 '14 at 08:05
  • Only do that if you want to kill your application. What you _really_ want is `Article.pluck("DISTINCT category")` – mrbrdo Apr 21 '15 at 10:14
7

I'd do it like this:

Article.select("distinct category").map {|a| a.category}

rather than lucapette's answer, because that kind of operations are far slower in ruby than in a database.

My code example is assuming that you're using some kind of SQL database by the way. It would look different with other kinds of databases.

Community
  • 1
  • 1
Frost
  • 11,121
  • 3
  • 37
  • 44
  • ...and this was of course an answer on how to do it in RubyOnRails, since the question was tagged that way. I didn't read that you were talking about a plain ruby Array, but assumed it had something to do with an ActiveRecord Model because of the `.all` method. – Frost Sep 19 '11 at 22:15
  • 2
    `Article.distinct("category").map(&:category)` might also work. – Frost Sep 19 '11 at 22:15
5

In Rails 3.2

Article.uniq.pluck(:category)
Rutger
  • 185
  • 2
  • 11
  • I am not sure if that's the correct answer. What if the category is the same for two Articles. The uniq, return are the unique articles, and then we map them to their categories. – Afshin Moazami Oct 30 '20 at 19:31