从Ruby中的字符串中删除最后2个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1392487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:43:27  来源:igfitidea点击:

Remove the last 2 characters from a string in Ruby?

ruby-on-railsruby

提问by Tom Lehman

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?

我怎样才能摆脱这个/是否有更好的方法来获取逗号分隔的电子邮件地址列表?

回答by DigitalRoss

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.

虽然这确实回答了确切的问题,但我同意这不是解决问题的最佳方法。

回答by giorgian

Use join:

使用连接:

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

回答by onyxrev

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

或者只是 "yadayada"[0..-3] 就可以了。