如何拆分散列中等于相同值的键(ruby)

问题描述 投票:0回答:1

>["nation", "nation", "nation"] => 3

["americans", "oath", "oath", "generation", "americans", "crisis", "crisis", "generation"] => 2,

所以现在我得到的所有这些键都等于相同的值(见上文),我想将它们拆分,以便每个单词=一个值,如下所示。

"nation" => 3
"oath" => 2
"crisis" => 2
ruby hash
1个回答
0
投票

听起来你正在寻找

Enumerable#tally
方法:

[
  "americans", "oath", "oath", "generation", "americans", "crisis", "crisis", "generation"
].tally
#=> { "americans" => 2, "oath" => 2, "generation" => 2, "crisis" =>2 }
© www.soinside.com 2019 - 2024. All rights reserved.