[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

count unique records

pustoi

12/8/2004 4:36:00 PM

Hello,

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

Thnx

2 Answers

Alexander Kellett

12/8/2004 4:47:00 PM

0

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
>



Brian Schröder

12/8/2004 5:16:00 PM

0

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
>
>

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-sch...