Tom Lehman
Tom Lehman

Reputation: 89203

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?

Upvotes: 14

Views: 22509

Answers (3)

DigitalRoss
DigitalRoss

Reputation: 146043

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.

Upvotes: 29

onyxrev
onyxrev

Reputation: 649

Or just "yadayada"[0..-3] will do it.

Upvotes: 13

giorgian
giorgian

Reputation: 3825

Use join:

def self.all_email_addresses
  User.all.collect {|u| u.email}.join ', '
end

Upvotes: 26

Related Questions