I have two bits of data I'm working with here.
A "question": This is an [example] string for [testing] and [what not].
And then I have an array of objects (called "answers") from my database:
[#<Answer id: 137, question_id: 207, text: "example">, #<Answer id: 138, question_id: 207, text: "testing">, #<Answer id: 139, question_id: 207, text: "what not"]
What I need to do is replace the bracketed text in the question ([example]
) with a link containing data from the corresponding object.
So [example]
might become <a href="#" data-answer="137" data-question="207">example</a>
.
How can I do that?
Assuming you have the answers already:
str = "This is an [example] string for [testing] and [what not]."
answers.each{|o| str.gsub!("[#{o.name}]", "<a href=\"#\" data-answer=\"#{o.id}\" data-question=\"#{o.question_id}\">#{o.name}</a>")}
If you don't have the answers:
str = "This is an [example] string for [testing] and [what not]."
m = str.scan(/\[([^\]]*)\]/).map{|s|s[0]}
Answer.where(:text => m).each{|o| str.gsub!("[#{o.name}]", "<a href=\"#\" data-answer=\"#{o.id}\" data-question=\"#{o.question_id}\">#{o.name}</a>")}
This works by using regex to search for all the text inbetween the [] brackets, which then returns an array to m. This array consists of ["example", "testing", "what not"].
You then pass that array into the where() call, which internally has SQL use an IN expression, such as WHERE text IN ('example','testing', 'what not')
After running this, str is now changed to your desired result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With