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


当前回答

我个人倾向于使用.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"

其他回答

你可以试试这个

"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"
s = "I have white space".delete(' ')

并模拟PHP的trim()函数:

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

我个人倾向于使用.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"

gsub方法就可以了。 gsub方法可以在字符串上调用,并说:

a = "this is a string"
a = a.gsub(" ","")
puts a
#Output: thisisastring

gsub方法搜索第一个参数的每一次出现 然后用第二个参数替换它。在这种情况下,它将替换字符串中的每个空格并删除它。

另一个例子:

b = "the white fox has a torn tail"

我们把所有出现的字母t都换成大写的t

b = b.gsub("t","T")
puts b 
#Output: The whiTe fox has a Torn Tail