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


当前回答

使用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   ".split
=> ["I", "have", "white", "space"]

现在说这个有点晚了,但是任何在谷歌上搜索这个页面的人都可能对这个版本感兴趣

如果你想清理一大块预先格式化的文本,用户可能以某种方式剪切和粘贴到你的应用程序,但保留单词间距,试试这个:

content = "      a big nasty          chunk of     something

that's been pasted                        from a webpage       or something        and looks 

like      this

"

content.gsub(/\s+/, " ").strip

#=> "a big nasty chunk of something that's been pasted from a webpage or something and looks like this"

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

例如:

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

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

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

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

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

String#rstrip -只从末尾开始。

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

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

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

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


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

"1232 23 2 23 232 232".delete(' ')
=> "123223223232232"

删除工作更快=)

user         system     total      real
gsub, s      0.180000   0.010000   0.190000 (0.193014)
gsub, s+     0.200000   0.000000   0.200000 (0.196408)
gsub, space  0.220000   0.000000   0.220000 (0.222711)
gsub, join   0.200000   0.000000   0.200000 (0.193478)
delete       0.040000   0.000000   0.040000 (0.045157)