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


当前回答

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

解决方案是:

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

其他回答

Ruby的.strip方法执行与trim()相当的PHP功能。

删除所有空白:

"  leading    trailing   ".squeeze(' ').strip
=> "leading trailing"

@塔斯让我意识到我原来的答案连续删除重复的字母-恶心!从那以后,我改用了压缩方法,如果使用Rails框架,这种方法对这种情况更聪明。

require 'active_support/all'
"  leading    trailing   ".squish
=> "leading trailing"

"  good    men   ".squish
=> "good men"

引用:http://apidock.com/rails/String/squish

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 >

这里有很多建议,但当我读到你的问题和说“删除所有空白”的具体行时,我想到的是:

" a b c " => "abc"

如果这确实是需要的,你可以做这个简单的操作

wide_string = " a b c "

narrow_string = wide_string.delete(" ")

# you can pass all the different kinds 
# of whitespaces that you want to remove

puts narrow_string # => "abc"

你可以试试这个:

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

为了得到这个:

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

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

"ab c d efg hi ".split.join

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

例如:

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

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

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