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


当前回答

Ruby的String的.scan()和.join()方法也可以帮助克服字符串中的空白。

扫描(\ w + /)。Join将删除所有空格并连接字符串

string = "White spaces in me".scan(/\w+/).join
=>"Whitespacesinme"

它还从字符串的左右部分删除空格。表示ltrim, rtrim和trim。以防万一有人有C, FoxPro或Visual Basic的背景,然后跳到Ruby。

2.1.6:002 > string = " White spaces in me ".scan(/\w+/).join = > " Whitespacesinme " 2.1.6:003 > string = " White spaces in me".scan(/\w+/).join = > " Whitespacesinme " 2.1.6:004 > string = "White spaces in me ".scan(/\w+/).join = > " Whitespacesinme " 2.1.6:005 >

其他回答

其实有一种更短更容易理解的方法。

为什么不直接分拆加入呢?

"s t r i n g".split(" ").join()
" Raheem Shaik ".strip

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

相关回答:

"   clean up my edges    ".strip

返回

"clean up my edges"

使用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"

你可以试试这个:

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

为了得到这个:

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

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

"ab c d efg hi ".split.join