Archivio mensile:settembre 2014

Ruby – Counting frequency of values in an Array

Based on a discussion on Ruby Forum here is an useful class for counting frequency of values in an array. So you can get easily the most frequent.

class Array
	def counts
		inject( Hash.new(0) ){ |hash,element|
			hash[ element ] +=1
			hash
		}
	end
	def counts_up
		counts.sort_by{ |k,v| v }
	end
	def counts_down
		counts.sort_by{ |k,v| -v }
	end
end
a = ["a", "a", "a", "b", "c", "c"]
p a.counts, a.counts_up, a.counts_down
#=> {"a"=>3, "b"=>1, "c"=>2}
#=> [["b", 1], ["c", 2], ["a", 3]]
#=> [["a", 3], ["c", 2], ["b", 1]]