从以下数组(哈希)开始:
我该如何添加重复URL的索引呢?例如:
[
{: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", :url=>"http://example.org/site/1/"},
{:name=>"site e", :url=>"http://example.org/site/2/"},
{: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},
{:name=>"site b", :url=>"http://example.org/site/2/", :index => 1},
{:name=>"site c", :url=>"http://example.org/site/3/", :index => 1},
{:name=>"site d", :url=>"http://example.org/site/1/", :index => 2},
{:name=>"site e", :url=>"http://example.org/site/2/", :index => 2},
{:name=>"site f", :url=>"http://example.org/site/6/", :index => 1},
{:name=>"site g", :url=>"http://example.org/site/1/", :index => 3}
]
each_with_object
,像这样:array.each_with_object(Hash.new(0)){ |counts, hash| hash[:index] = counts[hash[:url]] = counts[hash[:url]] + 1}
- fl00reach_with_object
。 - undur_gongor