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


当前回答

s = "I have white space".delete(' ')

并模拟PHP的trim()函数:

s = "   I have leading and trailing white space   ".strip

其他回答

删除两边的空白:

有点像php的trim()

"   Hello  ".strip

删除所有空格:

"   He    llo  ".gsub(/ /, "")

删除所有空白:

"   He\tllo  ".gsub(/\s/, "")

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

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

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"

相关回答:

"   clean up my edges    ".strip

返回

"clean up my edges"
s = "I have white space".delete(' ')

并模拟PHP的trim()函数:

s = "   I have leading and trailing white space   ".strip
"asd sda sda sd".gsub(' ', '')
=> "asdsdasdasd"