count unique records

P

pustoi

Hello,

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

Thnx
 
A

Alexander Kellett

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

Brian Schröder

On Thu, 9 Dec 2004 01:37:36 +0900
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top