15

I'm trying to grab data from a MySQL database and use Ruby to reformat it into a flat text file. Some of my MySQL data contains double quotes like so:

Matthew "Matt" Perry

and I need to remove those quotes and replace them with something else, | for instance.

I found another post on stackoverflow about removing quotes that suggested the following:

s.scan(/'(.+?)'|"(.+?)"|([^ ]+)/).flatten.compact

but that returns the string intact (with double quotes). How can I get

Matthew |Matt| Perry

instead?

4 Answers 4

24

This will do it if you don't want to modify s:

new_s = s.gsub /"/, '|'

If you do want to modify s:

s.gsub! /"/, '|'
0
5

You could use something like:

text = 'Matthew "Matt" Perry'

text.tr(%q{"'}, '|') # => "Matthew |Matt| Perry"

text = "Matthew 'Matt' Perry"
text.tr(%q{"'}, '|') # => "Matthew |Matt| Perry"
1
  • SO's syntax highlighter failed again )
    – Nakilon
    Jan 18, 2011 at 4:20
0

It removes doublequotes. You can see them in IRB or when using p only because string are being showed for you in these cases in nice form, allowing you to see, that they are strings.

irb> 'Matthew "Matt" Perry'.scan(/'(.+?)'|"(.+?)"|([^ ]+)/).flatten.compact
=> ["Matthew", "Matt", "Perry"]

In real, they already don't have doublequotes.

irb> puts 'Matthew "Matt" Perry'.scan(/'(.+?)'|"(.+?)"|([^ ]+)/).flatten.compact
Matthew
Matt
Perry
=> nil

And to replace doublequotes with dash, you may use .tr:

irb> 'Matthew "Matt" Perry'.tr '"','|'
=> "Matthew |Matt| Perry"
0
0

Other choices are:

s.tr! '"', '|'
s2 = s.tr '"', '|'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.