Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails: How can I replace a string with data from an array of objects?

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?

like image 753
Shpigford Avatar asked Sep 14 '25 14:09

Shpigford


1 Answers

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.

like image 144
Mike Lewis Avatar answered Sep 17 '25 04:09

Mike Lewis