Rahul Singh Rahul Singh - 4 months ago 26
Ruby Question

how to pluck email from array of users.?

if i do

User.all.pluck(:email)
then it works fine.

while if i do

arr = Array.new
arr = User.all


and then

arr.pluck(:email)


this gives me following error

undefined method `pluck' for #<Array:0x007f4ff8daf3c8>


which means i cannot use pluck with arrays, so how can we extract particular fields values from an array of records in just one line like above.
I don't want to loop through each reocrd in array.

Answer

pluck is useful to do a minimalist db query.

When you have an array, just use map:

arr.map(&:email)