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


当前回答

String#strip -删除开头和结尾的所有空白。

字符串#lstrip -只是从开始。

String#rstrip -只从末尾开始。

String#chomp(不带参数)-从末尾删除行分隔符(\n或\r\n)。

String#chop -删除最后一个字符。

x.delete(" \t\r\n")删除所有列出的空白。

String#gsub - x.gsub(/[[:space:]]/, ") -删除所有空白,包括unicode空白。


注意:上面所有的方法都返回一个新的字符串,而不是改变原来的字符串。如果您想就地更改字符串,请使用!最后。

其他回答

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

我有点晚了,但是我使用strip!来删除尾随和前导空格。如果您有一个数组,就像我所做的那样,我需要遍历该数组并在实例结束后保存它。!搞定了这个。这删除了结尾或开头的所有空格,而不仅仅是第一个前导或最后一个尾随。

例如:

array = ["hello ","   Melanie", "is", " new ", "to  ", " programming"]
array.each do |i|
  i.strip!
end

这将输出到:["hello","Melanie", "is", "new "," to", "programming"]。我在一个视频中进一步探讨/分享了这个问题,以突出这个代码来回答我遇到的类似问题。

我是较新的编程和使用strip不工作,因为它没有保存到循环结束后的数组。

相关回答:

"   clean up my edges    ".strip

返回

"clean up my edges"

别忘了:

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

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 >