Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ruby – 如何索引数组中的重复项?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
从以下数组(散列)开始:
[
  {:name=>"site a",:url=>"http://example.org/site/1/"},{:name=>"site b",:url=>"http://example.org/site/2/"},{:name=>"site c",:url=>"http://example.org/site/3/"},{:name=>"site d",{:name=>"site e",{:name=>"site f",:url=>"http://example.org/site/6/"},{:name=>"site g",:url=>"http://example.org/site/1/"}
]

如何添加重复URL的索引,如下所示:

[
  {:name=>"site a",:url=>"http://example.org/site/1/",:index => 1},:url=>"http://example.org/site/2/",:url=>"http://example.org/site/3/",:index => 2},:url=>"http://example.org/site/6/",:index => 3}
]

解决方法

我会使用哈希来跟踪索引.
一次又一次地扫描先前的条目似乎效率低下
counts = Hash.new(0)
array.each { | hash | 
  hash[:index] = counts[hash[:url]] = counts[hash[:url]] + 1
}

还是有点干净

array.each_with_object(Hash.new(0)) { | hash,counts | 
  hash[:index] = counts[hash[:url]] = counts[hash[:url]] + 1
}

大佬总结

以上是大佬教程为你收集整理的ruby – 如何索引数组中的重复项?全部内容,希望文章能够帮你解决ruby – 如何索引数组中的重复项?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。