Reputation: 823
in some video i saw next string:
User.select(:email).map(&:email)
tell me plz what does it means
i know that string
User.select(:email)
is selecting only the email column from the db, but i don't understand what means
.map(&:email)
and can we change User.select(:email)
to User.pluck(:email)
because from tutorial i understand thats the same methods. is this true?
Upvotes: 0
Views: 370
Reputation: 66
I suppose you already know what map(&:email) gives you, I assume you are asking how and why because it was the same thing that struck me when I first saw this. So this is one of the more advanced ruby magic that voodoo's results back to you :)
Basically lets look at the map function, in itself the most basic usage is to accept a block level command. And after iterating through, takes the default return value and chuck it into an array for you usage. For example, lets see this
list = User.all
so we get a list of user objects [User model,User model] etc.
list.map do |user|
user.email
end
if u run this block in IRB or Rails Console, you get ["[email protected], [email protected]"] etc. so lets catch this result and assign it into a variable
email_list = list.map do |user|
user.email
end
now email_list should equal to ["[email protected], [email protected]"] Now that you get the background to the map function, lets delve into the various ways it can accept a parameter
list.map {|user| user.email }
this is the same as the above, but using curly braces to enclose the block logic
list.map(&:email)
this is the shorthand for the above, by defining the block for you, you just supply what child function you wish to run on the block item.
Hope this has given you alittle insight into short hand methods and its block level equivalents.
Upvotes: 1
Reputation: 16012
User.select(:email)
is returning an array of User
objects. The expression
User.select(:email).map(&:email)
selects the email attribute of that objects only. So you end up with an array of email strings. That's at the end the same as
User.pluck(:email)
But it's is different from User.select(:email)
for that reason.
See the documentation of pluck als well.
Upvotes: 1
Reputation: 13925
The map(&:email)
maps your array of User
s to a map of string containing only the users' emails.
The Array.map iterates over your current array, and creates a new one, by calling the parameter block, and storing the result in the new array. It is equivalent with this:
new_array = []
Users.select(:email).each do |user|
new_array << user.email
end
Upvotes: 1