Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

regex

ruby

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 foo,bar:

  • "foo,bar"
  • "foo,bar
  • foo,bar"
  • foo,bar
like image 464
ChrisInEdmonton Avatar asked Aug 10 '10 20:08

ChrisInEdmonton


People also ask

How do you strip a quote from a string?

To remove double quotes just from the beginning and end of the String, we can use a more specific regular expression: String result = input. replaceAll("^\"|\"$", ""); After executing this example, occurrences of double quotes at the beginning or at end of the String will be replaced by empty strings.

How do you escape a double quote in Ruby?

In double quoted strings you would have to escape the backslash symbol to accomplish the same result. Examples of other escape sequences that work the same way are: \t , \s and \b , which represent a tab, a space and a backspace respectively.

What does =~ mean in Ruby?

=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.

What is the difference between single and double quotes in Ruby?

The basic difference between these two methods is Single quotes can not hold/print escape sequences directly, while double quotes can. i.e. Double quoted strings are used for String Interpolation in Ruby.


2 Answers

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/, '') 
like image 38
2 revs Avatar answered Oct 11 '22 16:10

2 revs


You could also use the chomp function, but it unfortunately only works in the end of the string, assuming there was a reverse chomp, you could:

'"foo,bar"'.rchomp('"').chomp('"') 

Implementing rchomp is straightforward:

class String   def rchomp(sep = $/)     self.start_with?(sep) ? self[sep.size..-1] : self   end end 

Note that you could also do it inline, with the slightly less efficient version:

'"foo,bar"'.chomp('"').reverse.chomp('"').reverse 

EDIT: Since Ruby 2.5, rchomp(x) is available under the name delete_prefix, and chomp(x) is available as delete_suffix, meaning that you can use

'"foo,bar"'.delete_prefix('"').delete_suffix('"') 
like image 186
grddev Avatar answered Oct 11 '22 17:10

grddev