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?
Use the String. slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.
In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.
Removing recurring characters in a string is easy to do in Ruby. We use the squeeze() method. The squeeze() method returns a new string with identical characters reduced to a single character. The squeeze() method can take an optional parameter.
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.
Use join:
def self.all_email_addresses
User.all.collect {|u| u.email}.join ', '
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With