如何提取给定属性的所有值并将它们放入数组中?

ale*_*ale 3 ruby ruby-on-rails-3 ruby-on-rails-3.2

我有一个看起来像这样的Ruby对象:

- !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
Run Code Online (Sandbox Code Playgroud)

该对象来自ActiveRecord查询.

我想获得bar这个对象中所有s 的数组,即

[3, 8, 1]
Run Code Online (Sandbox Code Playgroud)

在Ruby中有一些光滑的方式吗?

jor*_*ver 5

如果您只想要ActiveRecord查询中的一个属性,则可以使用pluck:

Foo.all.pluck(:bar)
Run Code Online (Sandbox Code Playgroud)

  • 我想你想要Foo.pluck(:吧) (2认同)