Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

count unique records

0 views
Skip to first unread message

pus...@spils.lv

unread,
Dec 8, 2004, 11:35:32 AM12/8/04
to
Hello,

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

Thnx

Alexander Kellett

unread,
Dec 8, 2004, 11:46:55 AM12/8/04
to
me bored
counts = array.inject(Hash.new { 0 }) { |counts, key| counts[key] += 1;
counts }
or something like that

Brian Schröder

unread,
Dec 8, 2004, 12:16:20 PM12/8/04
to

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

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

0 new messages