从以下数组(散列)开始:
[ {: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 }
原文地址:https://www.jb51.cc/ruby/264700.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。