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


当前回答

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

其他回答

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

并模拟PHP的trim()函数:

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

你可以试试这个:

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

为了得到这个:

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

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

"ab c d efg hi ".split.join

相关回答:

"   clean up my edges    ".strip

返回

"clean up my edges"

我会用这样的方法:

my_string = "Foo bar\nbaz quux"

my_string.split.join
=> "Foobarbazquux"

别忘了:

$ s = "   I have white space   ".split
=> ["I", "have", "white", "space"]