How to count duplicates in Ruby Arrays

后端 未结 16 1743
清歌不尽
清歌不尽 2020-12-01 06:21

How do you count duplicates in a ruby array?

For example, if my array had three a\'s, how could I count that

16条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 07:06

    To count instances of a single element use inject

    array.inject(0){|count,elem| elem == value ? count+1 : count}
    

提交回复
热议问题