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


当前回答

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

其他回答

s = "I have white space".delete(' ')

并模拟PHP的trim()函数:

s = "   I have leading and trailing white space   ".strip

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

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

你可以试试这个

"Some Special Text Values".gsub(/[[:space:]]+/, "")

使用:space:删除不间断的空格和常规空格。

相关回答:

"   clean up my edges    ".strip

返回

"clean up my edges"

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

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

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