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
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}