Ruby: Count unique elements and their occurences in an array
2024-08-20 07:18:25
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)
counts => {"A"=>4, "B"=>2, "C"=>1}
['A','A','A','A','B','B','C'].each { |name| counts[name] += 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_hOr 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}) }
最新文章
- [Hadoop] Hadoop学习历程 [持续更新中…]
- 关于Docker官方CentOS镜像无法启动mysqld的总结
- Windows 10 的音频和 MIDI API将统一
- IntelliJ IDEA 2016
- ios框架
- <;c:if>;标签判断是否为空
- 解决HP服务器安装Centos7 x64无法识别硬盘
- tomcat - 部署Web应用
- wcf系列学习5天速成——第四天 wcf之分布式架构
- 用c#实现与飞环语音卡的交互
- C语言老司机学Python (二)
- NFC驱动调试
- 前端JS 与 后台C# 之间JSON序列化与反序列化(笔记)
- 移动端触屏滑动touches使用
- [转].NET 性能测试工具 -- 事件跟踪器(ETW)
- Oracle导出csv时数字不变成科学计数法
- 分布式任务调度系统xxl-job搭建(基于docker)
- jquery及jquery常用选择器使用
- vscodes使用(一): 常用插件,在线与离线安装
- saprk2 structed streaming
热门文章
- Google Protocol Buffers和java字符串处理控制
- 趣味Java算法题(附答案)
- 【HDU】5256 系列转换(上涨时间最长的序列修饰)
- singleton pattern
- checkbox的attr(&;quot;checked&;quot;)一直以来,undefined问题解决
- StringUtils.isNumeric(String str) 的一个坑(转)
- paip.提高工作效率--数据绑定到table原则和过程Angular js jquery实现
- 《Linux Device Drivers》第十六章 块设备驱动程序——note
- Java泛型Restletclient
- 为RadComboBox添加SelectionChanging事件