How to strip leading and trailing quote from string, in Ruby

后端 未结 9 1477
栀梦
栀梦 2020-12-17 07:59

I want to strip leading and trailing quotes, in Ruby, from a string. The quote character will occur 0 or 1 time. For example, all of the following should be converted to f

相关标签:
9条回答
  • 2020-12-17 08:10

    Another approach would be

    remove_quotations('"foo,bar"')
    
    def remove_quotations(str)
      if str.start_with?('"')
        str = str.slice(1..-1)
      end
      if str.end_with?('"')
        str = str.slice(0..-2)
      end
    end 
    

    It is without RegExps and start_with?/end_with? are nicely readable.

    0 讨论(0)
  • 2020-12-17 08:17

    I can use gsub to search for the leading or trailing quote and replace it with an empty string:

    s = "\"foo,bar\""
    s.gsub!(/^\"|\"?$/, '')
    

    As suggested by comments below, a better solution is:

    s.gsub!(/\A"|"\Z/, '')
    
    0 讨论(0)
  • 2020-12-17 08:17

    You can strip non-optional quotes with scan:

    '"foo"bar"'.scan(/"(.*)"/)[0][0]
    # => "foo\"bar"
    
    0 讨论(0)
  • 2020-12-17 08:18

    Regexs can be pretty heavy and lead to some funky errors. If you are not dealing with massive strings and the data is pretty uniform you can use a simpler approach.

    If you know the strings have starting and leading quotes you can splice the entire string:

    string  = "'This has quotes!'"
    trimmed = string[1..-2] 
    puts trimmed # "This has quotes!"
    

    This can also be turned into a simple function:

    # In this case, 34 is \" and 39 is ', you can add other codes etc. 
    def trim_chars(string, char_codes=[34, 39])
        if char_codes.include?(string[0]) && char_codes.include?(string[-1])
            string[1..-2]
        else
            string
        end
    end
    
    0 讨论(0)
  • 2020-12-17 08:20

    I wanted the same but for slashes in url path, which can be /test/test/test/ (so that it has the stripping characters in the middle) and eventually came up with something like this to avoid regexps:

    '/test/test/test/'.split('/').reject(|i| i.empty?).join('/')
    

    Which in this case translates obviously to:

     '"foo,bar"'.split('"').select{|i| i != ""}.join('"')
    

    or

    '"foo,bar"'.split('"').reject{|i| i.empty?}.join('"')
    
    0 讨论(0)
  • 2020-12-17 08:23

    It frustrates me that strip only works on whitespace. I need to strip all kinds of characters! Here's a String extension that will fix that:

    class String
      def trim sep=/\s/
        sep_source = sep.is_a?(Regexp) ? sep.source : Regexp.escape(sep)
        pattern = Regexp.new("\\A(#{sep_source})*(.*?)(#{sep_source})*\\z")
        self[pattern, 2]
      end
    end
    

    Output

    '"foo,bar"'.trim '"'         # => "foo,bar"
    '"foo,bar'.trim '"'          # => "foo,bar"
    'foo,bar"'.trim '"'          # => "foo,bar"
    'foo,bar'.trim '"'           # => "foo,bar"
    
    '  foo,bar'.trim             # => "foo,bar"
    'afoo,bare'.trim /[aeiou]/   # => "foo,bar"
    
    0 讨论(0)
提交回复
热议问题