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


当前回答

gsub方法就可以了。 gsub方法可以在字符串上调用,并说:

a = "this is a string"
a = a.gsub(" ","")
puts a
#Output: thisisastring

gsub方法搜索第一个参数的每一次出现 然后用第二个参数替换它。在这种情况下,它将替换字符串中的每个空格并删除它。

另一个例子:

b = "the white fox has a torn tail"

我们把所有出现的字母t都换成大写的t

b = b.gsub("t","T")
puts b 
#Output: The whiTe fox has a Torn Tail

其他回答

Ruby的String的.scan()和.join()方法也可以帮助克服字符串中的空白。

扫描(\ w + /)。Join将删除所有空格并连接字符串

string = "White spaces in me".scan(/\w+/).join
=>"Whitespacesinme"

它还从字符串的左右部分删除空格。表示ltrim, rtrim和trim。以防万一有人有C, FoxPro或Visual Basic的背景,然后跳到Ruby。

2.1.6:002 > string = " White spaces in me ".scan(/\w+/).join = > " Whitespacesinme " 2.1.6:003 > string = " White spaces in me".scan(/\w+/).join = > " Whitespacesinme " 2.1.6:004 > string = "White spaces in me ".scan(/\w+/).join = > " Whitespacesinme " 2.1.6:005 >

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

并模拟PHP的trim()函数:

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

如果你只想删除开头和结尾的空白(就像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

我个人倾向于使用.tr方法

如:

string = "this is a string to smash together"

string.tr(' ', '') # => "thisisastringtosmashtogether"

感谢@FrankScmitt指出,要删除所有空白(不仅仅是空格),你需要这样写:

string = "this is a string with tabs\t and a \nnewline"

string.tr(" \n\t", '') # => "thisisastringwithtabsandanewline"