首页 文章

Ruby函数删除所有空格?

提问于
浏览
503

什么是删除 all 空格的Ruby函数?有点像php的 trim()

21 回答

  • 17

    也别忘了:

    $ s = "   I have white space   ".split
    => ["I", "have", "white", "space"]
    
  • 451
    s = "I have white space".delete(' ')
    

    并模拟PHP的 trim() 函数:

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

    这有点晚了,但是搜索此页面的任何人都可能对此版本感兴趣 -

    如果您要清理一大块预先格式化的文本,用户可能会以某种方式剪切并粘贴到您的应用中,但保留字间距,请尝试以下操作:

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

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

    scan(/\w+/).join 将删除所有空格并加入字符串

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

    它还从字符串的左右部分移除空间 . 意味着 ltrimrtrimtrim . 以防万一有人背景 CFoxProVisual 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 >

  • 1

    我会用这样的东西:

    my_string = "Foo bar\nbaz quux"
    
    my_string.split.join
    => "Foobarbazquux"
    
  • 6
    " Raheem Shaik ".strip
    

    它将删除左侧和右侧空格 . 这段代码会给我们: "Raheem Shaik"

  • 5

    我个人的偏好是使用方法 .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"
    
  • 7

    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
    
  • 74

    如果你只想删除前导空格和尾随空格(比如PHP的修剪)你可以使用 .strip ,但是如果你想删除 all 空格,你可以使用 .gsub(/\s+/, "") 代替 .

  • 44

    你可以试试这个:

    "ab c d efg hi ".split.map(&:strip)
    

    为了得到这个:

    ["ab, "c", "d", "efg", "hi"]
    

    或者如果你想要一个字符串,只需使用:

    "ab c d efg hi ".split.join
    
  • 6

    您可以使用 squish 方法 . 它删除字符串两端的空白区域,并将多个空格分组到单个空格 .

    例如 .

    " a  b  c ".squish
    

    将导致:

    "a b c"
    

    检查this reference from api.rubyonrails.org .

    编辑:它只适用于铁轨上的红宝石

  • 776
    "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)
    
  • 88

    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 ones .


    Note :上述所有方法都返回一个新字符串,而不是改变原始字符串 . 如果要更改字符串,请在末尾使用 ! 调用相应的方法 .

  • 25

    你可以试试这个

    "Some Special Text Values".gsub(/[[:space:]]+/, "")
    

    使用 :space: 删除非破坏空间以及常规空间 .

  • 2

    Ruby的 .strip 方法执行等效于 trim() 的PHP .

    要删除所有空格:

    "  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

  • 46

    我试图这样做,因为我想在视图中使用记录“title”作为id,但 Headers 有空格 .

    一个解决方案是:

    record.value.delete(' ') # Foo Bar -> FooBar
    
  • 1

    对于与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
    

    我创建了一个基准来测试 stripstrip! 的一些基本用途的性能,以及一些替代方案 . 测试是这样的:

    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)
    
  • -1
    "asd sda sda sd".gsub(' ', '')
    => "asdsdasdasd"
    
  • 2

    使用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"
    
  • 1

    相关回答:

    "   clean up my edges    ".strip
    

    回报

    "clean up my edges"
    
  • 20

    split.join 会爆炸字符串中任何位置的所有空格 .

    "  a b  c    d     ".split.join
    > "abcd"
    

    它很容易输入和记忆,所以它在控制台和快速黑客上都很好 . 可以说严格的代码不受欢迎,因为它掩盖了意图 .

    (根据Piotr在上述Justicle's answer中的评论 . )

相关问题