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


当前回答

分裂。Join将丢弃字符串中任何位置的所有空格。

"  a b  c    d     ".split.join
> "abcd"

它很容易输入和记忆,所以在控制台和快速破解上都很不错。在严肃的代码中可能不受欢迎,因为它掩盖了意图。

(基于上文justice的回答中Piotr的评论)

其他回答

我会用这样的方法:

my_string = "Foo bar\nbaz quux"

my_string.split.join
=> "Foobarbazquux"

相关回答:

"   clean up my edges    ".strip

返回

"clean up my edges"

如果你正在使用Rails/ActiveSupport,你可以使用挤压方法。它删除字符串两端的空白,并将多个空白分组为单个空格。

如。

" a  b  c ".squish

将导致:

"a b c"

查看api.rubyonrails.org的参考资料。

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

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

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

我个人倾向于使用.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"