1 Oct 2008 01:02
Re: Mode method for Array
Rob Biedenharn <Rob <at> AgileConsultingLLC.com>
2008-09-30 23:02:51 GMT
2008-09-30 23:02:51 GMT
On Sep 30, 2008, at 6:30 PM, Glenn wrote: > Hi, > > I wrote 2 ways. I don't know if either way is good or not. Any > feedback is welcome. > > The first way makes a hash of the array, with the unique values in > the array as the keys, and the number of times the keys occur as the > values. Then I create a new hash out of that first hash with the > frequencies as the keys of the hash and the elements that had that > frequency as the values. Then I pick out the value of the highest > key. > > The second way creates that frequency hash, then iterates over the > hash and creates an array with the elements that have the highest > frequency. > > class Array > def hash_of_frequency > h = Hash.new(0) > each_with_index do |e, i| > e = e.to_f if e != nil > h[e] = h[e] += 1 > end > h > end You never use i, so just use each (and loose the second block parameter) h[e] = h[e] += 1 ???(Continue reading)
RSS Feed