ChrisInEdmonton
ChrisInEdmonton

Reputation: 4578

How to strip leading and trailing quote from string, in 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:

Upvotes: 46

Views: 72701

Answers (9)

grddev
grddev

Reputation: 2852

Since Ruby 2.5, reverse chomp(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('"')

OLD ANSWER: For earlier Ruby versions, you could 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

Upvotes: 52

Yo Ludke
Yo Ludke

Reputation: 2269

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.

Upvotes: 10

marcinowski
marcinowski

Reputation: 359

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('"')

Upvotes: 3

flogram_dev
flogram_dev

Reputation: 42888

You can strip non-optional quotes with scan:

'"foo"bar"'.scan(/"(.*)"/)[0][0]
# => "foo\"bar"

Upvotes: -1

awendt
awendt

Reputation: 13723

Assuming that quotes can only appear at the beginning or end, you could just remove all quotes, without any custom method:

'"foo,bar"'.delete('"')

Upvotes: 4

Eva
Eva

Reputation: 4720

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"

Upvotes: 4

user427390
user427390

Reputation:

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

Upvotes: 0

ChrisInEdmonton
ChrisInEdmonton

Reputation: 4578

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/, '')

Upvotes: 43

the Tin Man
the Tin Man

Reputation: 160631

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.

Upvotes: 28

Related Questions