Count unique records

Hello,

Is there method in ruby like "uniq -c" command in Unix ?
uniq -c, --count prefix lines by the number of occurrences

Thnx

me bored
counts = array.inject(Hash.new { 0 }) { |counts, key| counts[key] += 1; counts }
or something like that

···

On Dec 8, 2004, at 5:37 PM, pustoi@spils.lv wrote:

Hello,

Is there method in ruby like "uniq -c" command in Unix ?
uniq -c, --count prefix lines by the number of occurrences

Thnx

You can implement uniq -c like this:

#!/usr/bin/ruby

(ARGF.read.split($/) << nil).inject([nil, 0]) do | (last_line, count), line |
  if last_line and line != last_line
    puts(("%7d " % count) + last_line)
    count = 0
  end
  [line, count+1]
end

Use:

bschroed@black:~/svn/projekte/ruby-things $ cat send.rb | uniq -c
      1 class A
      1 def send_it method_name
      1 send(method_name, "Send from #{self}")
      1 end
      1 end
      1
      1 class B < A
      1 def select(msg)
      1 puts "Received: #{msg}"
      1 end
      1 end
      1
      1 b = B.new
      1 b.send_it(:select)
bschroed@black:~/svn/projekte/ruby-things $ cat send.rb | ./uniq-count
      1 class A
      1 def send_it method_name
      1 send(method_name, "Send from #{self}")
      1 end
      1 end
      1
      1 class B < A
      1 def select(msg)
      1 puts "Received: #{msg}"
      1 end
      1 end
      1
      1 b = B.new
      1 b.send_it(:select)
bschroed@black:~/svn/projekte/ruby-things $ cat send.rb | sort | uniq -c
      2
      1 b = B.new
      1 b.send_it(:select)
      1 class A
      1 class B < A
      1 def select(msg)
      1 def send_it method_name
      2 end
      2 end
      1 puts "Received: #{msg}"
      1 send(method_name, "Send from #{self}")
bschroed@black:~/svn/projekte/ruby-things $ cat send.rb | sort | ./uniq-count
      2
      1 b = B.new
      1 b.send_it(:select)
      1 class A
      1 class B < A
      1 def select(msg)
      1 def send_it method_name
      2 end
      2 end
      1 puts "Received: #{msg}"
      1 send(method_name, "Send from #{self}")

regards,

Brian

···

On Thu, 9 Dec 2004 01:37:36 +0900 pustoi@spils.lv wrote:

Hello,

Is there method in ruby like "uniq -c" command in Unix ?
uniq -c, --count prefix lines by the number of occurrences

Thnx

--
Brian Schröder
http://www.brian-schroeder.de/