去除所有空白的Ruby函数是什么?我正在寻找一些类似于PHP的trim()?


当前回答

其实有一种更短更容易理解的方法。

为什么不直接分拆加入呢?

"s t r i n g".split(" ").join()

其他回答

其实有一种更短更容易理解的方法。

为什么不直接分拆加入呢?

"s t r i n g".split(" ").join()

别忘了:

$ s = "   I have white space   ".split
=> ["I", "have", "white", "space"]

如果你正在使用Rails/ActiveSupport,你可以使用挤压方法。它删除字符串两端的空白,并将多个空白分组为单个空格。

如。

" a  b  c ".squish

将导致:

"a b c"

查看api.rubyonrails.org的参考资料。

相关回答:

"   clean up my edges    ".strip

返回

"clean up my edges"

现在说这个有点晚了,但是任何在谷歌上搜索这个页面的人都可能对这个版本感兴趣

如果你想清理一大块预先格式化的文本,用户可能以某种方式剪切和粘贴到你的应用程序,但保留单词间距,试试这个:

content = "      a big nasty          chunk of     something

that's been pasted                        from a webpage       or something        and looks 

like      this

"

content.gsub(/\s+/, " ").strip

#=> "a big nasty chunk of something that's been pasted from a webpage or something and looks like this"