I am trying to create method to switch words in string with keywords from hash. For example, there is the string:
my_string = "France france USA usa ENGLAND england ENGland"
Here is my hash:
my_hash = {"england" => "https://google.com"}
And there is the loop:
occurrences = {}
my_string.gsub!(/\w+/) do |match|
key = my_hash[match.downcase]
count = occurrences.store(key, occurrences.fetch(key, 0).next)
count > 2 ? match : "<a href = #{key}>#{match}</a>"
end
The output of this loop is:
<a href = >France</a> <a href = >france</a> USA usa <a href = https://google.com>ENGLAND</a> <a href = https://google.com>england</a> ENGland
Expected output:
France france USA usa <a href = https://google.com>ENGLAND</a> <a href = https://google.com>england</a> ENGland
The problem you see here is that my loop always took over an <a href>
tag the first two words from string, no matter if they are in the hash or not (as you can see in 'France' example) and it should work as in 'England' example (the first two 'Englands' became a hyperlinks but not the third, as it should work).
P.S - additional question: is there any way to avoid already existing hyperlinks in string and not to touch them? For example - if there already would be an 'England' hyperlink in string but with another href.