I'm trying to collect emails from a group of people using the following:
def representative_email(group)
group.representatives.collect{ |m|
rep.Us开发者_Go百科er.find(m.user_id)
rep.email
}
end
However this is producing results like: ["email@email.com", "email2@email.com"]
How can I remove all []
and ""
and leave only:
email@email.com, email2@email.com
In fact, it would be better to replace the comma with a semi-colon as well.
def representative_email(group)
group.representatives.collect{ |m|
rep.User.find(m.user_id)
rep.email
}.join('; ')
end
The result of your function (i.e. the result of Array#collect
) is an Array
; the brackets and the quotes are artifacts introduced by the way the Array
got converted into a String
. If you control the conversion process, it generally goes better - in that you know exactly what you receive.
In this case, you can use Array#join
which sticks the string representation of an Array
together, using the argument String
as a glue.
Probably, you saw that though p
or inspect
. The double quotations are not part of the strings. They are just ways of representing strings literary. And the brackets and the commas represent that they are within an array. They are just there when you see them through p
or inspect
. If you want to see how they actually look like, use puts
.
What you're seeing is the "stringified" version of the Array you've created. If you want it formatted in a different manner, you should do something like this when you call it:
emails = representative_email(group).join(';')
You should also be very careful when using find
as it can and will throw an ActiveRecord::RecordNotFound exception if it can't find what you're looking for, so you must be prepared to rescue this. I'm not sure what you're trying to do here with the call to User.find
seemingly out of place, either.
精彩评论