tags:

views:

105

answers:

3

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
A: 

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/, '')
ChrisInEdmonton
A couple of hints: there is no need to escape the quotes in the `Regexp`, since quotes don't have any special meaning in `Regexp` s anyway. Also, `^` and `$` *do not* anchor to the beginning and end of the *string*, they anchor to the beginning and end of the *line*. It's not clear from your question which one of the two you want: if you want to remove quotes from the beginning and end of the string, you need to use `\A` and `\Z` instead. Lastly, you can get rid of the escapes for the double quotes (and the confusing double double quotes) by delimiting your string with single quotes.
Jörg W Mittag
Altogether, it looks like this: ` s = '"foo,bar"'; s.gsub!(/\A"|\Z"$/, '') ` (I forgot: there's also no need to make the match optional. If it doesn't match, then simply nothing will get replaced.)
Jörg W Mittag
@Jörg, don't you mean `s.gsub!(/\A"|"\Z/, '')`?
grddev
@grddev: Yes, of course. This comment box makes a terrible IDE :-)
Jörg W Mittag
+1  A: 

As usual everyone grabs regex from the toolbox first. :-)

As an alternate I'll recommend looking into .tr('"', '') (AKA "translate") which, in this use, is really stripping the quotes.

Greg
Assuming there are no `"` in the middle of the string.
grddev
According to the examples given by the OP there are only leading/trailing double-quotes so it's a safe assumption.
Greg
It's not a safe assumption, but I didn't specifically state that there could be a quote inside the string. Nevertheless, it's a good answer and one most definitely worth my +1.
ChrisInEdmonton
+1  A: 

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
grddev
Interesting approach. I expected someone to provide an answer involving array indices [0] and [-1], but had forgotten about chomp, an obviously better solution. I think your answer is better than mine.
ChrisInEdmonton