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


当前回答

使用gsub或delete。区别在于gsub可以删除制表符,而delete不能。有时文件中确实有编辑器添加的选项卡。

a = "\tI have some whitespaces.\t"
a.gsub!(/\s/, '')  #=>  "Ihavesomewhitespaces."
a.gsub!(/ /, '')   #=>  "\tIhavesomewhitespaces.\t"
a.delete!(" ")     #=>  "\tIhavesomewhitespaces.\t"
a.delete!("/\s/")  #=>  "\tIhavesomewhitespaces.\t"
a.delete!('/\s/')  #=>  using single quote is unexpected, and you'll get "\tI have ome whitepace.\t"

其他回答

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

并模拟PHP的trim()函数:

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

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

如。

" a  b  c ".squish

将导致:

"a b c"

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

相关回答:

"   clean up my edges    ".strip

返回

"clean up my edges"

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

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

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