meoww-
meoww-

Reputation: 1892

Regex Pattern Matching to an array

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.

Upvotes: 0

Views: 73

Answers (2)

sawa
sawa

Reputation: 168081

st.gsub!(/{{(.*?)}}/).with_object([]){|_, a| a.push($1); $1} #=> ["brown", "fence"]
st #=> "The quick brown fox jumped over the fence."

Upvotes: 2

falsetru
falsetru

Reputation: 368954

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"]

Upvotes: 3

Related Questions