删除所有空格的Ruby函数?
删除所有空格的Ruby函数是什么?我正在寻找类似PHP的删除所有空格的Ruby函数?,ruby,string,Ruby,String,删除所有空格的Ruby函数是什么?我正在寻找类似PHP的trim() 要模拟PHP的trim()函数: s = " I have leading and trailing white space ".strip 相关答复: " clean up my edges ".strip 返回 "clean up my edges" 也不要忘记: $ s = " I have white space ".split => ["I", "have", "white",
trim()
要模拟PHP的trim()
函数:
s = " I have leading and trailing white space ".strip
相关答复:
" clean up my edges ".strip
返回
"clean up my edges"
也不要忘记:
$ s = " I have white space ".split
=> ["I", "have", "white", "space"]
如果您只想删除前导和尾随的空格(如PHP的trim),可以使用
.strip
,但是如果您想删除所有的空格,可以使用.gsub(/\s+/,“”)
。现在有点晚了,但是谷歌搜索此页面的其他人可能对此版本感兴趣-
如果您想清除用户可能以某种方式剪切粘贴到应用程序中的预格式化文本块,但保留单词间距,请尝试以下操作:
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"
"ab c d efg hi ".split.map(&:strip)
Ruby的
.strip
方法执行相当于trim()
的PHP
要删除所有空白,请执行以下操作:
" leading trailing ".squeeze(' ').strip
=> "leading trailing"
" He\tllo ".gsub(/\s/, "")
@塔斯社让我意识到,我原来的答案会连续删除重复的字母-恶心!此后,我切换到了squish方法,如果使用Rails框架,这种方法对此类事件更为明智
require 'active_support/all'
" leading trailing ".squish
=> "leading trailing"
" good men ".squish
=> "good men"
引用:
删除速度更快=)
它将删除左侧和右侧的空格。
这段代码将告诉我们:
“Raheem Shaik”
如果您使用的是Rails/ActiveSupport,那么您可以使用squish
方法。它删除字符串两端的空白,并将多个空白分组为单个空白
例如
" a b c ".squish
将导致:
"a b c"
选中。
拆分。join
将清除字符串中任何位置的所有空格
" a b c d ".split.join
> "abcd"
它很容易输入和记住,因此在控制台上很好,并且可以快速进行黑客攻击。在严肃的代码中可能不受欢迎,因为它掩盖了意图
(根据Piotr在上面的评论。)你可以试试这个
"Some Special Text Values".gsub(/[[:space:]]+/, "")
使用:空格:删除不间断空格和常规空格。使用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"
我个人的偏好是使用
.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"
Ruby的.scan()
和.join()
字符串方法也可以帮助克服字符串中的空白
扫描(/\w+/)。join
将删除所有空格并加入字符串
string = "White spaces in me".scan(/\w+/).join
=>"Whitespacesinme"
它还从字符串的左、右部分删除了空格。表示ltrim
,rtrim
和trim
。以防有人有C
、FoxPro
或visualbasic
的背景,然后跳入Ruby
2.1.6:002>string=“我的空格”。扫描(/\w+/)。加入
=>“Whitespacesinme”
2.1.6:003>string=“me中的空格”。扫描(/\w+/)。加入
=>“Whitespacesinme”
2.1.6:004>string=“我的空格”。扫描(/\w+/)。加入
=>“Whitespacesinme”
2.1.6 :005 >
对于与PHPtrim
完全匹配的行为,最简单的方法是使用String#strip
方法,如下所示:
string = " Many have tried; many have failed! "
puts "Original [#{string}]:#{string.length}"
new_string = string.strip
puts "Updated [#{new_string}]:#{new_string.length}"
Ruby还有一个原地编辑版本,名为String.strip代码>(注意后面的“!”)。这不需要创建字符串的副本,并且在某些用途下可以大大加快速度:
string = " Many have tried; many have failed! "
puts "Original [#{string}]:#{string.length}"
string.strip!
puts "Updated [#{string}]:#{string.length}"
两个版本都会产生此输出:
Original [ Many have tried; many have failed! ]:40
Updated [Many have tried; many have failed!]:34
我创建了一个基准测试来测试strip
和strip的一些基本用法的性能代码>,以及一些备选方案。测试是这样的:
require 'benchmark'
string = 'asdfghjkl'
Times = 25_000
a = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
b = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
c = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
d = Times.times.map {|n| spaces = ' ' * (1+n/4); "#{spaces}#{spaces}#{string}#{spaces}" }
puts RUBY_DESCRIPTION
puts "============================================================"
puts "Running tests for trimming strings"
Benchmark.bm(20) do |x|
x.report("s.strip:") { a.each {|s| s = s.strip } }
x.report("s.rstrip.lstrip:") { a.each {|s| s = s.rstrip.lstrip } }
x.report("s.gsub:") { a.each {|s| s = s.gsub(/^\s+|\s+$/, "") } }
x.report("s.sub.sub:") { a.each {|s| s = s.sub(/^\s+/, "").sub(/\s+$/, "") } }
x.report("s.strip!") { a.each {|s| s.strip! } }
x.report("s.rstrip!.lstrip!:") { b.each {|s| s.rstrip! ; s.lstrip! } }
x.report("s.gsub!:") { c.each {|s| s.gsub!(/^\s+|\s+$/, "") } }
x.report("s.sub!.sub!:") { d.each {|s| s.sub!(/^\s+/, "") ; s.sub!(/\s+$/, "") } }
end
结果如下:
ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-darwin14]
============================================================
Running tests for trimming strings
user system total real
s.strip: 2.690000 0.320000 3.010000 ( 4.048079)
s.rstrip.lstrip: 2.790000 0.060000 2.850000 ( 3.110281)
s.gsub: 13.060000 5.800000 18.860000 ( 19.264533)
s.sub.sub: 9.880000 4.910000 14.790000 ( 14.945006)
s.strip! 2.750000 0.080000 2.830000 ( 2.960402)
s.rstrip!.lstrip!: 2.670000 0.320000 2.990000 ( 3.221094)
s.gsub!: 13.410000 6.490000 19.900000 ( 20.392547)
s.sub!.sub!: 10.260000 5.680000 15.940000 ( 16.411131)
-删除开头和结尾的所有空格
-从一开始
-从最后开始
(无参数)-从末尾删除行分隔符(\n
或\r\n
)
-删除最后一个字符
-x.delete(“\t\r\n”)
-删除所有列出的空白
-x.gsub(/[:space:][]/,'')
-删除所有空白,包括
注意:上述所有方法都返回一个新字符串,而不是对原始字符串进行变异。如果要在适当的位置更改字符串,请使用调用相应的方法代码>结尾。我试图这样做,因为我想在视图中使用记录“标题”作为id,但标题中有空格
解决办法是:
record.value.delete(' ') # Foo Bar -> FooBar
您可以尝试以下方法:
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"
"ab c d efg hi ".split.map(&:strip)
为了实现这一点:
["ab, "c", "d", "efg", "hi"]
或者,如果需要单个字符串,只需使用:
"ab c d efg hi ".split.join
我会用这样的方式:
my_string = "Foo bar\nbaz quux"
my_string.split.join
=> "Foobarbazquux"
gsub方法就可以了。
可以对字符串调用gsub方法,并表示:
a = "this is a string"
a = a.gsub(" ","")
puts a
#Output: thisisastring
gsub方法搜索第一个参数的每次出现
并用第二个参数替换它。在这种情况下,它将替换字符串中的每个空格并将其删除
另一个例子:
b = "the white fox has a torn tail"
array = ["hello "," Melanie", "is", " new ", "to ", " programming"]
array.each do |i|
i.strip!
end
让我们用大写字母“t”替换字母“t”
要删除两侧的空白,请执行以下操作:
有点像php的trim()
要删除所有空格,请执行以下操作:
" He llo ".gsub(/ /, "")
要删除所有空白,请执行以下操作:
" leading trailing ".squeeze(' ').strip
=> "leading trailing"
" He\tllo ".gsub(/\s/, "")
我玩游戏有点晚了,但我使用strip删除了尾随和前导空格代码>。如果您有一个数组,如我所做的,我需要遍历该数组并在实例结束后保存它。这个处理好这件事。这将删除结尾或开头的所有空白,而不仅仅是第一个前导或最后一个尾随
例如:
b = "the white fox has a torn tail"
array = ["hello "," Melanie", "is", " new ", "to ", " programming"]
array.each do |i|
i.strip!
end
这将输出到:[“hello”、“Melanie”、“is”、“new”、“to”、“programming”]。我进一步探讨/分享了这一点
我刚开始编程,使用strip不起作用,因为循环结束后它没有将其保存到数组中。这是我忘记的一个。我知道有一种删除空白的方法,如果没有传递任何参数,默认情况下会这样做+1这相当于修剪。请参考上面@Tadeck的引用。如果变量可能是nil
array = ["hello "," Melanie", "is", " new ", "to ", " programming"]
array.each do |i|
i.strip!
end