chell chell - 2 months ago 8
Ruby Question

How to remove the {} and \" from the resulting array using ruby

I have a text string as follows:

my_string = 'The {"apples" >> "apple"} {"do" >> "does"} not fall far from {+"the "}tree{"?" >> "!"}'


I extract all of the content between the braces { } into an array using the following:

my_content = my_string.scan(/\{.*?\}/)


The result is:

["{\"apples\" >> \"apple\"}",
"{\"do\" >> \"does\"}",
"{+\"the \"}",
"{\"?\" >> \"!\"}"]


I would like to have the content as:

["apples >> apple", "do >> does", "+the ", "? >> !"]


I do this in a very noob(and bad) way as follows:

my_content = eval my_content.to_s.gsub('\"','')
my_content = eval my_contents.to_s.gsub('{','')
my_content = eval my_content.to_s.gsub('}','')


How can I remove the elements I don't want to include correctly?

Answer
▶ my_string.scan(/(?<={).*?(?=})/).map { |s| s.delete '"' } 
#⇒ ["apples >> apple", "do >> does", "+the ", "? >> !"]

On the first step we use positive lookaround, on the second one—geting rid of double quotes.