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


当前回答

现在说这个有点晚了,但是任何在谷歌上搜索这个页面的人都可能对这个版本感兴趣

如果你想清理一大块预先格式化的文本,用户可能以某种方式剪切和粘贴到你的应用程序,但保留单词间距,试试这个:

content = "      a big nasty          chunk of     something

that's been pasted                        from a webpage       or something        and looks 

like      this

"

content.gsub(/\s+/, " ").strip

#=> "a big nasty chunk of something that's been pasted from a webpage or something and looks like this"

其他回答

现在说这个有点晚了,但是任何在谷歌上搜索这个页面的人都可能对这个版本感兴趣

如果你想清理一大块预先格式化的文本,用户可能以某种方式剪切和粘贴到你的应用程序,但保留单词间距,试试这个:

content = "      a big nasty          chunk of     something

that's been pasted                        from a webpage       or something        and looks 

like      this

"

content.gsub(/\s+/, " ").strip

#=> "a big nasty chunk of something that's been pasted from a webpage or something and looks like this"

删除两边的空白:

有点像php的trim()

"   Hello  ".strip

删除所有空格:

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

删除所有空白:

"   He\tllo  ".gsub(/\s/, "")

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

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

如果你只想删除开头和结尾的空白(就像PHP的trim一样),你可以使用.strip,但如果你想删除所有的空白,你可以使用.gsub(/\s+/, "")。

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