我最近在一次采訪中被問到這個問題,并且正在想辦法在 Ruby 中不使用正則運算式來做到這一點,因為我被告知如果你可以在不使用正則運算式的情況下解決它,那將是一個獎勵。
問題:假設散列有 100 萬個鍵、值對,我們必須能夠對字串中位于% %
此模式之間的變數進行子分類。如果沒有正則運算式,我怎么能做到這一點。
我們有一個字串str = "%greet%! Hi there, %var_1% that can be any other %var_2% injected to the %var_3%. Nice!, goodbye)"
我們有一個哈希叫做dict = { greet: 'Hi there', var_1: 'FIRST VARIABLE', var_2: 'values', var_3: 'string', }
這是我的解決方案:
def template(str, dict)
vars = value.scan(/%(.*?)%/).flatten
vars.each do |var|
value = value.gsub("%#{var}%", dict[var.to_sym])
end
value
end
uj5u.com熱心網友回復:
一個非常簡單的方法:
首先,將字串拆分為'%'
:
str = "%greet%! Hi there, %var_1% that can be any other %var_2% injected to the %var_3%. Nice!, goodbye)"
chunks = str.split('%')
現在我們可以假設給定問題的指定方式,每個其他“塊”都將是替換的關鍵。使用索引進行迭代將更容易弄清楚。
chunks.each_with_index { |c, i| chunks[i] = (i.even? ? c : dict[c.to_sym]) }.join
結果:
"Hi there! Hi there, FIRST VARIABLE that can be any other values injected to the string. Nice!, goodbye)"
注意:這根本不能很好地處理格式錯誤的輸入。
uj5u.com熱心網友回復:
有很多方法可以解決這個問題,但如果您不想使用內置模式匹配,則可能需要某種決議和/或詞法分析。
讓我們保持非常簡單,并說您的字串內容分為兩類:文本和變數,由 分隔%
,例如
str = "Hello %name%, hope to see you %when%!"
# TTTTTT VVVV TTTTTTTTTTTTTTTTTT VVVV T
如您所見,類別是交替的。我們可以利用它并撰寫一個小助手方法,將字串轉換為[type, value]
對串列,如下所示:
def each_part(str)
return enum_for(__method__, str) unless block_given?
type = [:text, :var].cycle
buf = ''
str.each_char do |char|
if char != '%'
buf << char
else
yield type.next, buf
buf = ''
end
end
yield type.next, buf
end
它首先定義一個將cycle
在兩種型別之間的列舉器和一個空緩沖區。然后它將each_char
從字串中讀取。如果 char 不是%
,它只會將其附加到緩沖區并繼續閱讀。一旦遇到 a %
,它會將yield
當前緩沖區與型別一起啟動并啟動一個新緩沖區(next
也將切換type
)。回圈結束后,將yield
再次輸出剩余的字符。
它輸出這種資料:
each_part(str).to_a
#=> [[:text, "Hello "],
# [:var, "name"],
# [:text, ", hope to see you "],
# [:var, "when"],
# [:text, "!"]]
我們可以使用它來轉換字串:
dict = { name: 'Tom', when: 'soon' }
output = ''
each_part(str) do |type, value|
case type
when :text
output << value
when :var
output << dict[value.to_sym]
end
end
p output
#=> "Hello Tom, hope to see you soon!"
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/495303.html