From: Brian Candler Date: 2008-10-01T16:34:47+09:00 Subject: Re: Mode method for Array Shame that the standard Hash#invert doesn't handle duplicate values well. My suggestion: class Hash def ninvert inject({}) { |h,(k,v)| (h[v] ||= []) << k; h } end end class Array def get_mode (inject(Hash.new(0)) { |h,e| h[e] += 1; h }.ninvert.max || [[]]).last end end p [3, 1, 1, 55, 55].get_mode p [3, 1, 1, 55].get_mode p [:foo, 3, "bar", :foo, 4, "bar"].get_mode p [].get_mode (with ruby 1.8 if there are multiple mode values you get them in an arbitary order; I think with 1.9 you'd get them in the order first seen in the original array) -- Posted via http://www.ruby-forum.com/.