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


当前回答

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

其他回答

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

别忘了:

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

你可以试试这个:

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

为了得到这个:

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

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

"ab c d efg hi ".split.join

我试图这样做,因为我想使用记录“标题”作为视图中的id,但标题有空格。

解决方案是:

record.value.delete(' ') # Foo Bar -> FooBar

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

例如:

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

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

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