我正試圖創建一種方法,用哈希的關鍵詞來切換字串中的單詞。例如,有一個字串:
my_string = "France france USA USA ENGLAND ENGland"
這是我的哈希:
my_hash = {"england"/span> => "https://google.com"}
這就是回圈:
occurrences = {}.
my_string.gsub! (/w /) do |match|
key = my_hash[match.downncase]
count = occurrences.store(key, occurrences.fetch(key, 0).next)
count > 2 ? match : "<a href=#{key}>#{match}</a> "
end。
這個回圈的輸出是:
<a href = > 法國</a> < a href = >france</a> 美國usa <a href = https: //google. com>ENGLAND</a> < a href = https: //google. com>england</a> ENGland
預期輸出:
France 法國 USA 美國 <a href = https://google. com>ENGLAND</a> < a href = https: //google. com>england</a> ENGland
你在這里看到的問題是,我的回圈總是從一個<a href>標簽中獲取字串中的前兩個詞,無論它們是否在哈希中(正如你在'France'例子中看到的那樣),它應該像'England'例子中那樣作業(前兩個'Englands'成為一個超鏈接,而不是第三個,因為它應該作業)。
P.S - 另外一個問題:是否有辦法避免字串中已經存在的超鏈接,而不去觸碰它們?例如,如果字串中已經有一個 "英格蘭 "的超鏈接,但有另一個href。
uj5u.com熱心網友回復:
my_string = "France france USA USA ENGLAND ENGland"
my_hash = {"england"=> "https://google.com"}
my_string.split
.chunk(&: downcase)
.flat_map do |country,a|
a.flat_map.with_index do |s,i|
if i < 2 && my_hash.key? (country)
"<a href=#{my_hash[country]}>#{s}</a>"/span>
else
s
end
end end
end.join(')
#=> "France法國 USA美國 <a href=https://google.com>ENGLAND</a> <a href=https://google.com>England</a> ENGland"
參見Enumerable#chunk和Enumerable#flat_map.
注意
enum0 = my_string.split.chunk(&: downcase)
#=> #<列舉者。#<Enumerator::Generator:0x00007ff90c13bc28>:each>/span>
通過將該列舉器轉換為陣列,可以看到該列舉器生成的值。
enum0.to_a
#=> [["france", ["France", "france"]], ["USA", ["USA"]] 。
# ["england", ["ENGLAND", "england", "ENGland"] ]]
然后
enum1 = enum0.flat_map
#=> #<列舉者。#<列舉者: #<Enumerator::Generator:0x00007ff90c113e58>:each>:flat_map>/span>
由enum1生成并分配給兩個塊變數的初始值如下:
country, a = enum1.next
#=> ["france", ["France", "france" ]]
國家
#=> "france"] 國家
a #=> ["France", "france"]
uj5u.com熱心網友回復:
從你的問題中我并不完全清楚你想要的輸出是什么,但是如果你想只替換與你的哈希中的某個鍵相匹配的詞,只需在你的哈希查找后添加一個if(或一個next)。另外,變數key被用來存盤這個查找的value,所以我重新命名了它,并且在occurrences哈希中增加了key而不是value。這似乎更符合你的要求。
occurrences = {}.
my_string.gsub! (/w /) do |match|
key = match.downncase
value = my_hash[key]
next unless value
count = occurrences.store(key, occurrences.fetch(key, 0).next)
count > 2 ? match : "<a href=#{value}>#{match}</a> "
end。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/307011.html
標籤:
下一篇:如何在rails中更新空列的值?
