简体   繁体   中英

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

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.

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:

User.pluck(:firstname, :lastname)

You can also collect "firstname, lastname":

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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