Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract all values of a given attribute and put them into an array?

I have a Ruby object that looks like this:

- !ruby/object:Foo
  attributes:
    updated: 2013-07-30 13:30:21.589221000 Z
    bar: 3
- !ruby/object:Statistic
  attributes:
    updated: 2013-07-30 13:30:28.017951000 Z
    bar: 8
- !ruby/object:Statistic
  attributes:
    updated: 2013-07-30 13:30:39.514180000 Z
    bar: 1

The object comes from an ActiveRecord query.

I would like to get an array of all the bars in this object i.e.

[3, 8, 1]

Is there some slick way of doing this in Ruby?

like image 345
ale Avatar asked Sep 08 '25 12:09

ale


1 Answers

If you only want one attribute from an ActiveRecord query, you can use pluck:

Foo.all.pluck(:bar)
like image 176
jordelver Avatar answered Sep 10 '25 01:09

jordelver