Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the last 2 characters from a string in Ruby?

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?

like image 490
Tom Lehman Avatar asked Sep 08 '09 07:09

Tom Lehman


People also ask

How do I remove the last 3 characters from a string?

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.

How do you remove a character from a string in Ruby?

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.

How do I remove duplicate characters in a string in Ruby?

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.


2 Answers

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.

like image 161
DigitalRoss Avatar answered Oct 09 '22 05:10

DigitalRoss


Use join:

def self.all_email_addresses
  User.all.collect {|u| u.email}.join ', '
end
like image 34
giorgian Avatar answered Oct 09 '22 07:10

giorgian