Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby code for modifying outer quotes on strings?

Tags:

string

ruby

quote

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?

like image 741
Blue Avatar asked Dec 12 '10 22:12

Blue


2 Answers

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.

like image 106
Mark Thomas Avatar answered Nov 15 '22 08:11

Mark Thomas


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"
like image 41
the Tin Man Avatar answered Nov 15 '22 07:11

the Tin Man