去除所有空白的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"

删除两边的空白:

有点像php的trim()

"   Hello  ".strip

删除所有空格:

"   He    llo  ".gsub(/ /, "")

删除所有空白:

"   He\tllo  ".gsub(/\s/, "")
"asd sda sda sd".gsub(' ', '')
=> "asdsdasdasd"

你可以试试这个

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

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

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

解决方案是:

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