ruby code for modifying outer quotes on strings?
Asked Answered
L

3

6

Does anyone know of a Ruby gem (or built-in, or native syntax, for that matter) that operates on the outer quote marks of strings?

I find myself writing methods like this over and over again:

remove_outer_quotes_if_quoted( myString, chars ) -> aString
add_outer_quotes_unless_quoted( myString, char ) -> aString

The first tests myString to see if its beginning and ending characters match any one character in chars. If so, it returns the string with quotes removed. Otherwise it returns it unchanged. chars defaults to a list of quote mark characters.

The second tests myString to see if it already begins and ends with char. If so, it returns the string unchanged. If not, it returns the string with char tacked on before and after, and any embedded occurrance of char is escaped with backslash. char defaults to the first in a default list of characters.

(My hand-cobbled methods don't have such verbose names, of course.)

I've looked around for similar methods in the public repos but can't find anything like this. Am I the only one that needs to do this alot? If not, how does everyone else do this?

Luannaluanne answered 12/12, 2010 at 22:13 Comment(7)
You may want to look at why you do this a lot. A little root-cause analysis may help you make your code cleaner.Lingua
@Mark Thomas: If I could up vote your comment more, I would. Since it seems to me that there is a deeper underlying problem.Atmosphere
Heh heh. The root cause is that I'm working with a few different APIs, each of which quotes the same data slightly differently. I don't really have any control over them.Luannaluanne
"I find myself writing methods like this over and over again". Then don't do that. Follow the "DRY" mantra and "don't repeat yourself"; Make a tiny module that extends String and require it in your code.Seigneury
@Greg: Exactly. So DRY, in fact, that I thought I'd ask around first to see if there wasn't already some gem out in the wild that does something like this.Luannaluanne
@Blue, good point. If you're already using Rails, or pulling in parts of ActiveSupport, you can probably find something already written and piggyback on that. Otherwise, I'd extend String and not worry about some other gem. If you found one, odds are good you'd end up pulling in a lot more code that didn't get used, offsetting the advantage DRY-wise.Seigneury
Don't forget to mark answers as accepted if they've solved your questions.Hyphen
L
4

If you do it a lot, you may want to add a method to String:

class String
  def strip_quotes
    gsub(/\A['"]+|['"]+\Z/, "")
  end
end

Then you can just call string.strip_quotes.

Adding quotes is similar:

class String
  def add_quotes
     %Q/"#{strip_quotes}"/ 
  end
end

This is called as string.add_quotes and uses strip_quotes before adding double quotes.

Lingua answered 13/12, 2010 at 0:30 Comment(1)
Be advised the code above will potentially strip mismatched quotes and will remove multiple quotes from either/both ends of the string is there are any. It does not care if both are " or ', it just strips them.Congruity
S
3

This might 'splain how to remove and add them:

str1 = %["We're not in Kansas anymore."]
str2 = %['He said, "Time flies like an arrow, Fruit flies like a banana."']

puts str1
puts str2

puts

puts str1.sub(/\A['"]/, '').sub(/['"]\z/, '')
puts str2.sub(/\A['"]/, '').sub(/['"]\z/, '')

puts 

str3 = "foo"
str4 = 'bar'

[str1, str2, str3, str4].each do |str|
  puts (str[/\A['"]/] && str[/['"]\z/]) ? str : %Q{"#{str}"}
end

The original two lines:

# >> "We're not in Kansas anymore."
# >> 'He said, "Time flies like an arrow, Fruit flies like a banana."'

Stripping quotes:

# >> We're not in Kansas anymore.
# >> He said, "Time flies like an arrow, Fruit flies like a banana."

Adding quotes when needed:

# >> "We're not in Kansas anymore."
# >> 'He said, "Time flies like an arrow, Fruit flies like a banana."'
# >> "foo"
# >> "bar"
Seigneury answered 13/12, 2010 at 0:2 Comment(1)
Thanks for the suggestions. I have written methods of my own (which have to deal with strings like %['Twas the night before Christmas] and %['This is illogical"], among other anomalies) but was just wondering if I was reinventing the wheel here.Luannaluanne
A
0

I would use the value = value[1...-1] if value[0] == value[-1] && %w[' "].include?(value[0]). In short, this simple code checks whether first and last char of string are the same and removes them if they are single/double quote. Additionally as many as needed quote types can be added.

%w["adadasd" 'asdasdasd' 'asdasdasd"].each do |value|
  puts 'Original value: ' + value
  value = value[1...-1] if value[0] == value[-1] && %w[' "].include?(value[0])
  puts 'Processed value: ' + value
end

The example above will print the following:

Original value: "adadasd"
Processed value: adadasd
Original value: 'asdasdasd'
Processed value: asdasdasd
Original value: 'asdasdasd"
Processed value: 'asdasdasd"
Axinomancy answered 28/12, 2017 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.