Gareth Burrows
Gareth Burrows

Reputation: 1182

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?

Upvotes: 2

Views: 266

Answers (1)

Thomas
Thomas

Reputation: 1633

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}"}

Upvotes: 5

Related Questions