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


当前回答

" Raheem Shaik ".strip

它将删除左边和右边的空格。 这段代码会给我们"拉希姆·谢克"

其他回答

String#strip -删除开头和结尾的所有空白。

字符串#lstrip -只是从开始。

String#rstrip -只从末尾开始。

String#chomp(不带参数)-从末尾删除行分隔符(\n或\r\n)。

String#chop -删除最后一个字符。

x.delete(" \t\r\n")删除所有列出的空白。

String#gsub - x.gsub(/[[:space:]]/, ") -删除所有空白,包括unicode空白。


注意:上面所有的方法都返回一个新的字符串,而不是改变原来的字符串。如果您想就地更改字符串,请使用!最后。

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

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

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"

如果你只想删除开头和结尾的空白(就像PHP的trim一样),你可以使用.strip,但如果你想删除所有的空白,你可以使用.gsub(/\s+/, "")。

你可以试试这个

"Some Special Text Values".gsub(/[[:space:]]+/, "")

使用:space:删除不间断的空格和常规空格。

使用gsub或delete。区别在于gsub可以删除制表符,而delete不能。有时文件中确实有编辑器添加的选项卡。

a = "\tI have some whitespaces.\t"
a.gsub!(/\s/, '')  #=>  "Ihavesomewhitespaces."
a.gsub!(/ /, '')   #=>  "\tIhavesomewhitespaces.\t"
a.delete!(" ")     #=>  "\tIhavesomewhitespaces.\t"
a.delete!("/\s/")  #=>  "\tIhavesomewhitespaces.\t"
a.delete!('/\s/')  #=>  using single quote is unexpected, and you'll get "\tI have ome whitepace.\t"