2011-03-30 39 views
2

我在這裏處理了兩位數據。Ruby/Rails:如何用對象數組中的數據替換字符串?

A「問題」:This is an [example] string for [testing] and [what not].

後來才知​​道有對象的數組(稱爲「答案」),從我的數據庫:

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

我需要做的是替換括號內的文字該問題([example])帶有包含來自相應對象的數據的鏈接。因此[example]可能變成<a href="#" data-answer="137" data-question="207">example</a>

我該怎麼做?

+0

你知道事先使用什麼答案,或者您首先必須提取括號內的文本,然後搜索數據庫? – DanneManne 2011-03-30 01:51:00

+0

我有事先的答案。 – Shpigford 2011-03-30 02:33:59

+0

由於'Answer'是您的自定義類,因此您已告知如何在「Answer」實例中訪問id和問題標識。否則,不可能回答。 – sawa 2011-03-30 02:44:55

回答

6

假設你已經有答案已經:

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>")} 

如果您還沒有答案:

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>")} 

這是通過使用正則表達式來搜索所有的文字插圖中[]括號,然後將數組返回給m。這個數組由[「example」,「testing」,「what not」]組成。

您然後傳遞該陣列進入其中()調用,其內部具有SQL使用IN表達式,如WHERE text IN ('example','testing', 'what not')

運行此之後,str是現在改變爲您的期望的結果。

+0

??最近5分鐘我一直在寫這個。 (我實際上創建了一個答案模型^ _ ^) – 2011-03-30 02:03:09

+1

偉大的思想,我想。 +1好的措施 – Kelly 2011-03-30 02:06:39

+0

非常真實。老實說,我會在幾分鐘內創建答案頁面,當我提交答案時。我看到有人已經有了一個類似的答案。對不起,凱利。 – 2011-03-30 02:07:54

0
s = "This is an [example] string for [testing] and [what not]" 
=> "This is an [example] string for [testing] and [what not]" 
h = {id: 137, question_id: 207, text: "example"} 
=> {:id=>137, :question_id=>207, :text=>"example"} 

s.sub(/\[example\]/, %Q{<a href="#" data-answer="#{h[:id]}" data-question="#{h[:question_id]}">#{h[:text]}</a>}) 
=> "This is an <a href=\"#\" data-answer=\"137\" data-question=\"207\">example</a> string for [testing] and [what not]" 
2

如果你不希望有從數據庫中獲取整個表,你可以搜索這些括號的字符串,然後再對數據庫執行搜索:

str = "This is an [example] string for [testing] and [what not]." 
matches = str.scan(/\[([^\]]*)\]/).collect { |s|s[0]} 
Answer.where(:text => matches).each{|o| str.gsub!("[#{o.name}]", "<a href=\"#\" data-answer=\"#{o.id}\" data-question=\"#{o.question_id}\">#{o.name}</a>")} 
+2

我只是建議使用%Q {},所以你不必逃避所有的雙引號。 – Wes 2011-03-30 04:52:24

相關問題