简体   繁体   English

使用Ruby收集多个变量

[英]Using Ruby collect with more than 1 variable

Sure this is a simple one, but is it possible to return more than 1 attribute with collect 当然这是一个简单的方法,但是使用collect可以返回多个属性

So I can do 所以我可以做

User.all.collect { |user| user.firstname}

but I can't do 但我做不到

User.all.collect { |user| user.firstname, user.lastname}

What am I missing? 我想念什么?

collect returns an array. collect返回一个数组。

You can make it an array of pairs: 您可以使其成对排列:

User.all.collect { |user| [user.firstname, user.lastname]}

With ActiveRecord pluck , you can have the same result with a more efficient request: 使用ActiveRecord pluck ,您可以通过更有效的请求获得相同的结果:

User.pluck(:firstname, :lastname)

You can also collect "firstname, lastname": 您还可以collect “名字,姓氏”:

User.all.collect { |user| "#{user.firstname}, #{user.lastname}"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM