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


当前回答

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

其他回答

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

你可以试试这个

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

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

"asd sda sda sd".gsub(' ', '')
=> "asdsdasdasd"

你可以试试这个:

"ab c d efg hi ".split.map(&:strip)

为了得到这个:

["ab, "c", "d", "efg", "hi"]

或者如果你想要一个字符串,只需使用:

"ab c d efg hi ".split.join
s = "I have white space".delete(' ')

并模拟PHP的trim()函数:

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