Re: Making a count of unique elements in an array


#1

Dan K. [mailto:removed_email_address@domain.invalid] wrote:

#counter = {}
#arr.each {|e| counter[e] += 1 rescue counter[e] = 1 }
#p counter.to_a

me, like the above but w slight modif below:

irb(main):013:0> counter2 = Hash.new(0)
=> {}
irb(main):014:0> arr.each {|e| counter2[e] += 1 }
=> [“a”, “b”, “b”, “c”, “c”, “d”, “e”, “e”, “e”]
irb(main):015:0> counter2.to_a
=> [[“a”, 1], [“b”, 2], [“c”, 2], [“d”, 1], [“e”, 3]]
irb(main):016:0>

(note the plain counter and the hash param)

hth.

kind regards -botp