Path: csiph.com!x330-a1.tempe.blueboxinc.net!aioe.org!news.swapon.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.ruby Subject: Re: Counting how many times the same elements occurs in an array? Date: Sun, 15 May 2011 13:52:34 +0200 Lines: 48 Message-ID: <939t4dF4vaU1@mid.individual.net> References: <6a81112b3af069fa30e1c843c72f8be9@ruby-forum.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net sf+2rKtu34Mt7h12273vggZUMBBsf+gNiTEHUTJMOQkdDSzk8= Cancel-Lock: sha1:lmhT34sRgHsxMePJtpaM9aKmUSw= User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.17) Gecko/20110414 Lightning/1.0b2 Thunderbird/3.1.10 In-Reply-To: <6a81112b3af069fa30e1c843c72f8be9@ruby-forum.com> X-Antivirus: avast! (VPS 110515-0, 15.05.2011), Outbound message X-Antivirus-Status: Clean Xref: x330-a1.tempe.blueboxinc.net comp.lang.ruby:4563 On 15.05.2011 12:01, Thomas Greenwood wrote: > There's probably a fairly simple way to do this. > > Basically I'm reading data from an xml file, I need to figure out how > many times identical data occurs in certain attributes, so far I've got > the data into two identical arrays and had the intention of nesting > iterators - seeing if the element was equal to the second and > incrementing every time a match was found. That obviously didn't work > out the way I initially thought. > > This seems to be the jist of what I want but it's obviously returning a > count on every iteraton whereas I only want the final tally. > > xml_events.each{|x| > puts "#{x} occurs #{xml_events.count(x)} times" > } > > Any ideas? Two possible approaches: irb(main):002:0> a = Array.new(10) { rand(4) } => [3, 2, 2, 1, 3, 3, 2, 3, 3, 3] irb(main):003:0> a.inject(Hash.new(0)) {|sums,x| sums[x] += 1; sums} => {3=>6, 2=>3, 1=>1} irb(main):004:0> a.group_by {|x| x} => {3=>[3, 3, 3, 3, 3, 3], 2=>[2, 2, 2], 1=>[1]} irb(main):005:0> a.group_by {|x| x}.map {|k,v| [k, v.size]} => [[3, 6], [2, 3], [1, 1]] Instead of #inject you can of course also use a more traditional approach: irb(main):012:0> counts = Hash.new 0 => {} irb(main):013:0> a.each {|x| counts[x] += 1} => [3, 2, 2, 1, 3, 3, 2, 3, 3, 3] irb(main):014:0> counts => {3=>6, 2=>3, 1=>1} Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/