gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:53:09 25 4
gpt4 key购买 nike

我有一个看起来像这样的 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

对象来自 ActiveRecord 查询。

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

[3, 8, 1]

在 Ruby 中有一些巧妙的方法可以做到这一点吗?

最佳答案

如果您只想从 ActiveRecord 查询中获取一个属性,您可以使用 pluck :

Foo.all.pluck(:bar)

关于ruby - 如何提取给定属性的所有值并将它们放入数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17956289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com