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

后端 未结 9 1481
栀梦
栀梦 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: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
    

提交回复
热议问题