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


当前回答

删除两边的空白:

有点像php的trim()

"   Hello  ".strip

删除所有空格:

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

删除所有空白:

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

其他回答

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

并模拟PHP的trim()函数:

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

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

你可以试试这个

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

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

相关回答:

"   clean up my edges    ".strip

返回

"clean up my edges"

我个人倾向于使用.tr方法

如:

string = "this is a string to smash together"

string.tr(' ', '') # => "thisisastringtosmashtogether"

感谢@FrankScmitt指出,要删除所有空白(不仅仅是空格),你需要这样写:

string = "this is a string with tabs\t and a \nnewline"

string.tr(" \n\t", '') # => "thisisastringwithtabsandanewline"