Rahul Singh Rahul Singh - 4 months ago 13
Ruby Question

how to pluck email from array of users?

If I do

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

But 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)