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


当前回答

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

其他回答

我个人倾向于使用.tr方法

如:

string = "this is a string to smash together"

string.tr(' ', '') # => "thisisastringtosmashtogether"

感谢@FrankScmitt指出,要删除所有空白(不仅仅是空格),你需要这样写:

string = "this is a string with tabs\t and a \nnewline"

string.tr(" \n\t", '') # => "thisisastringwithtabsandanewline"

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

别忘了:

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

我会用这样的方法:

my_string = "Foo bar\nbaz quux"

my_string.split.join
=> "Foobarbazquux"
"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)