joe*_*ely 821
如果你只想删除前导空格和尾随空格(比如PHP的修剪)你可以使用.strip,但是如果要删除所有空格,可以.gsub(/\s+/, "")改用.
Ed *_* S. 482
s = "I have white space".delete(' ')
并模拟PHP的trim()功能:
s = "   I have leading and trailing white space   ".strip
jrh*_*cks 160
相关回答:
"   clean up my edges    ".strip
回报
"clean up my edges"
ndn*_*kov 143
String#strip - 从开头和结尾删除所有空格.
String#lstrip - 从一开始.
String#rstrip - 就在最后.
String#chomp(没有参数) - 从末尾删除行分隔符(\n或\r\n).
String#chop - 删除最后一个字符.
String#delete- x.delete(" \t\r\n")- 删除所有列出的空格.
String#gsub- x.gsub(/[[:space:]]/, '')- 删除所有空格,包括unicode空格.
注意:上述所有方法都返回一个新字符串,而不是改变原始字符串.如果要更改字符串,请!在最后调用相应的方法.
rus*_*ils 93
"1232 23 2 23 232 232".delete(' ')
=> "123223223232232"
删除工作更快=)
user         system     total      real
gsub, s      0.180000   0.010000   0.190000 (0.193014)
gsub, s+     0.200000   0.000000   0.200000 (0.196408)
gsub, space  0.220000   0.000000   0.220000 (0.222711)
gsub, join   0.200000   0.000000   0.200000 (0.193478)
delete       0.040000   0.000000   0.040000 (0.045157)
Rad*_*ika 81
你可以使用squish方法.它删除字符串两端的空白区域,并将多个空格分组为单个空格.
例如.
" a  b  c ".squish
将导致:
"a b c"
编辑:它只适用于铁轨上的红宝石
Jul*_*and 47
这有点晚了,但是搜索此页面的任何人都可能对此版本感兴趣 -
如果你想清理用户可能以某种方式剪切并粘贴到你的应用程序中的一大块预格式化文本,但保留字间距,试试这个:
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"
sca*_*er2 45
Ruby的.strip方法执行PHP等价于trim().
要删除所有空格:
"  leading    trailing   ".squeeze(' ').strip
=> "leading trailing"
@Tass让我知道我的原始答案连续删除了重复的字母 - 你好!我已经改用了squish方法,如果使用Rails框架,这种方法更聪明.
require 'active_support/all'
"  leading    trailing   ".squish
=> "leading trailing"
"  good    men   ".squish
=> "good men"
引用:http://apidock.com/rails/String/squish
小智 25
" Raheem Shaik ".strip
它将删除左侧和右侧空间.这段代码会给我们:"Raheem Shaik"
Sap*_*ick 25
要删除两边的空格:
有点像 php 的 trim()
"   Hello  ".strip
删除所有空格:
"   He    llo  ".gsub(/ /, "")
要删除所有空格:
"   He\tllo  ".gsub(/\s/, "")
Jus*_*cle 20
也别忘了:
$ s = "   I have white space   ".split
=> ["I", "have", "white", "space"]
mah*_*off 19
split.join 会爆炸弦中任何地方的所有空间.
"  a b  c    d     ".split.join
> "abcd"
它很容易输入和记忆,所以它在控制台和快速黑客上都很好.虽然因为它掩盖了意图,但严重的代码可能不受欢迎.
(基于Piotr在上面的Justicle答案中的评论.)
小智 10
你可以试试这个
"Some Special Text Values".gsub(/[[:space:]]+/, "")
using :space:删除非破坏空间和常规空间.
使用gsub或删除.不同的是gsub可以删除标签,而删除不能.有时,您确实在编辑器添加的文件中有选项卡.
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"
小智 7
很多建议在这里都有效,但是当我读到你的问题和“删除所有空白”的具体行时,我想到的是:
" a b c " => "abc"
如果这确实是所需要的,您可以执行这个简单的操作
" a b c " => "abc"
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
对于与PHP完全匹配的行为trim,最简单的方法是使用该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)
| 归档时间: | 
 | 
| 查看次数: | 510264 次 | 
| 最近记录: |