首页 > 解决方案 > 使用哈希问题中的关键字切换字符串中的单词

问题描述

我正在尝试创建方法来使用哈希中的关键字切换字符串中的单词。例如,有一个字符串:

my_string = "France france USA usa ENGLAND england ENGland"

这是我的哈希:

my_hash = {"england" => "https://google.com"}

还有循环:

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

这个循环的输出是:

 <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

预期输出:

France france USA usa <a href = https://google.com>ENGLAND</a> <a href = https://google.com>england</a> ENGland

您在这里看到的问题是我的循环总是从字符串中接管<a href>前两个单词的标签,无论它们是否在哈希中(如您在“France”示例中所见),它应该像在“England”中一样工作' 示例(前两个“英格兰”成为超链接,但不是第三个,因为它应该可以工作)。

PS - 附加问题:有没有办法避免字符串中已经存在的超链接而不是触摸它们?例如 - 如果字符串中已经有一个“英格兰”超链接但带有另一个 href。

标签: ruby-on-railsiteration

解决方案


my_string = "France france USA usa ENGLAND 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>"
              else
                s    
              end
            end
          end.join(' ')
  #=> "France france USA usa <a href = https://google.com>ENGLAND</a> <a href = https://google.com>england</a> ENGland"

请参阅Enumerable#chunkEnumerable#flat_map

注意

enum0 = my_string.split.chunk(&:downcase)
  #=> #<Enumerator: #<Enumerator::Generator:0x00007ff90c13bc28>:each>

该枚举器生成的值可以通过将其转换为数组来查看。

enum0.to_a
  #=> [["france", ["France", "france"]], ["usa", ["USA", "usa"]],
  #    ["england", ["ENGLAND", "england", "ENGland"]]]

然后

enum1 = enum0.flat_map
  #=> #<Enumerator: #<Enumerator: #<Enumerator::Generator:0x00007ff90c113e58>:each>:flat_map>

由两个块变量生成并分配给的初始值enum1如下。

country, a = enum1.next
  #=> ["france", ["France", "france"]] 
country
  #=> "france"
a #=> ["France", "france"]

推荐阅读