0

I have a string defined as follows:

st = "The quick {{brown}} fox jumped over the {{fence}}." 

To remove the {{ }}, I am doing the following:

st.gsub(/{{(.*?)}}/, '\1') 
=> "The quick brown fox jumped over the fence." 

What I would like to do now is put each of the items that matched the regular expression into an array, so that the end result looks like:

arr = []
puts arr => ['brown', 'fence']
puts st => "The quick brown fox jumped over the fence." 

Thanks in advance.

2 Answers 2

3

String#gsub, String#gsub! accepts optional block parameter. The return value of the block is used as a replacement string.

st = "The quick {{brown}} fox jumped over the {{fence}}."
arr = []
st.gsub!(/{{(.*?)}}/) { |m| arr << $1; $1 }
st
# => "The quick brown fox jumped over the fence."
arr
# => ["brown", "fence"]
Sign up to request clarification or add additional context in comments.

1 Comment

Can't accept this answer for 10 minutes, but this is the answer and it works fine in my IRB. Will accept soon :-) Thanks!
2
st.gsub!(/{{(.*?)}}/).with_object([]){|_, a| a.push($1); $1} #=> ["brown", "fence"]
st #=> "The quick brown fox jumped over the fence."

1 Comment

@CarySwoveland Yes. You are right. I first had it, and then somehow removed it. I was wrong.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.