How to group numbers into different buckets in Ruby

后端 未结 3 1719
轮回少年
轮回少年 2021-01-01 02:51

I have a file with numbers on each line:

0101
1010
1311
0101
1311
431
1010
431
420

I want have a hash with the number of occurrences of eac

3条回答
  •  [愿得一人]
    2021-01-01 03:34

    This is essentially the same as Chuck's, but when you are creating an array or hash, 'each_with_object' will make it slightly simpler than 'inject', as you do not have to write the final array or hash in the block.

    items.each_with_object(Hash.new(0)) {|item, hash| hash[item] += 1}
    

提交回复
热议问题