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


当前回答

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

" 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"

其他回答

相关回答:

"   clean up my edges    ".strip

返回

"clean up my edges"
"asd sda sda sd".gsub(' ', '')
=> "asdsdasdasd"

你可以试试这个:

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

为了得到这个:

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

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

"ab c d efg hi ".split.join
" Raheem Shaik ".strip

它将删除左边和右边的空格。 这段代码会给我们"拉希姆·谢克"

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

如。

" a  b  c ".squish

将导致:

"a b c"

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