How to group numbers into different buckets in Ruby

后端 未结 3 1740
轮回少年
轮回少年 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:33

    Simple one-liner, given an array items:

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

    How it works:

    Hash.new(0) creates a new Hash where accessing undefined keys returns 0.

    inject(foo) iterates through an array with the given block. For the first iteration, it passes foo, and on further iterations, it passes the return value of the last iteration.

    Another way to write it would be:

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

提交回复
热议问题