Forum: Ruby Re: Making a count of unique elements in an array

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
6087a044557d6b59ab52e7dd20f94da8?d=identicon&s=25 Peña, Botp (Guest)
on 2006-01-09 08:09
(Received via mailing list)
Dan Kohn [] 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 =
=> {}
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]]

(note the plain counter and the hash param)


kind regards -botp
This topic is locked and can not be replied to.