Is there a method in Ruby that takes an array, and counts all unique elements and their occurrences and passes them back as a hash?

For example

  ['A','A','A','A','B','B','C'].method
> {'A' => 4, 'B' => 2, 'C' => 1}

Something like that.

['A','A','A','A','B','B','C'].group_by{|e| e}.map{|k, v| [k, v.length]}.to_h

src = ['A','A','A','A','B','B','C']
Hash[src.group_by { |x| x }.map { |k, v| [k, v.length] }]
counts = Hash.new(0)
['A','A','A','A','B','B','C'].each { |name| counts[name] += 1 }
counts => {"A"=>4, "B"=>2, "C"=>1}

['A','A','A','A','B','B','C'].each_with_object(Hash.new(0)) { |l, o| o[l] += 1 }

This is the easiest readable for me:

src = ['A','A','A','A','B','B','C']
src.group_by(&:to_s).to_a.map { |a| [a[0], a[1].count] }.to_h

Or here is another solution with reduce method:

src.reduce({}) { |b, a| b.merge({a => (b[a] || 0) + 1}) }

Or:

src.reduce(Hash.new(0)) { |b, a| b.merge({a => b[a] + 1}) }

最新文章

  1. [Hadoop] Hadoop学习历程 [持续更新中…]
  2. 关于Docker官方CentOS镜像无法启动mysqld的总结
  3. Windows 10 的音频和 MIDI API将统一
  4. IntelliJ IDEA 2016
  5. ios框架
  6. <c:if>标签判断是否为空
  7. 解决HP服务器安装Centos7 x64无法识别硬盘
  8. tomcat - 部署Web应用
  9. wcf系列学习5天速成——第四天 wcf之分布式架构
  10. 用c#实现与飞环语音卡的交互
  11. C语言老司机学Python (二)
  12. NFC驱动调试
  13. 前端JS 与 后台C# 之间JSON序列化与反序列化(笔记)
  14. 移动端触屏滑动touches使用
  15. [转].NET 性能测试工具 -- 事件跟踪器(ETW)
  16. Oracle导出csv时数字不变成科学计数法
  17. 分布式任务调度系统xxl-job搭建(基于docker)
  18. jquery及jquery常用选择器使用
  19. vscodes使用(一): 常用插件,在线与离线安装
  20. saprk2 structed streaming

热门文章

  1. Google Protocol Buffers和java字符串处理控制
  2. 趣味Java算法题(附答案)
  3. 【HDU】5256 系列转换(上涨时间最长的序列修饰)
  4. singleton pattern
  5. checkbox的attr("checked")一直以来,undefined问题解决
  6. StringUtils.isNumeric(String str) 的一个坑(转)
  7. paip.提高工作效率--数据绑定到table原则和过程Angular js jquery实现
  8. 《Linux Device Drivers》第十六章 块设备驱动程序——note
  9. Java泛型Restletclient
  10. 为RadComboBox添加SelectionChanging事件