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/