I'm collecting all my user's email addresses for a mass mailing like this:
我正在收集所有用户的电子邮件地址,如下所示:
def self.all_email_addresses
output = ''
User.all.each{|u| output += u.email + ", " }
output
end
However, I end up with an extra ", " on the string of email addresses.
但是,我最终在电子邮件地址字符串上添加了一个“,”。
How can I get rid of this / is there a better way to get a comma separated list of email addresses?
我怎样才能摆脱这个/有更好的方法来获得逗号分隔的电子邮件地址列表?
3 个解决方案
#1
26
Use join:
使用加入:
def self.all_email_addresses
User.all.collect {|u| u.email}.join ', '
end
#2
27
remove the last two characters
str.chop.chop # ...or...
str[0..-3]
Although this does answer the exact question, I agree that it isn't the best way to solve the problem.
虽然这确实回答了确切的问题,但我同意这不是解决问题的最佳方法。
#3
12
Or just "yadayada"[0..-3] will do it.
或者只是“yadayada”[0 ..- 3]会这样做。
#1
26
Use join:
使用加入:
def self.all_email_addresses
User.all.collect {|u| u.email}.join ', '
end
#2
27
remove the last two characters
str.chop.chop # ...or...
str[0..-3]
Although this does answer the exact question, I agree that it isn't the best way to solve the problem.
虽然这确实回答了确切的问题,但我同意这不是解决问题的最佳方法。
#3
12
Or just "yadayada"[0..-3] will do it.
或者只是“yadayada”[0 ..- 3]会这样做。