ruby-on-rails - 使用哈希问题中的关键字切换字符串中的单词
问题描述
我正在尝试创建方法来使用哈希中的关键字切换字符串中的单词。例如,有一个字符串:
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。
解决方案
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#chunk和Enumerable#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"]
推荐阅读
- linux - 无法使用旧内核分支构建。好像每次都取最近的一张
- javascript - 如何将 Firestore 中的现有集合/数据移动到子集合?
- go - 去测试终端输出
- c# - 使用单元测试、工作单元和通用存储库模式框架从 MOQ 获取单个对象
- python - Python,附加到列表时出现类错误
- python - GTK 加速器重定向
- angular - 如何将选择的文本从外部应用程序拖放到 Angular 12 应用程序中?
- firebase - 点击书籍时如何显示书籍详情
- python - qiskit install error 命令出错,退出状态为 1:
- python - 在谷歌应用程序上应用过滤器