At Thu, 17 Jun 2004 16:48:21 +0900,
Ralf M?ller wrote:
> 
> 11111111111111111111111111111111111111111111111111111111111111
> ram@lilith:~/src/ruby$cat rec_pi.rb 
> n = STDIN.gets
>   tot = 0
>   9.times do |i|
>     c = n.count(i.to_s)
>     tot += c
>     puts "#{i} #{c}"
>   end
>   puts "9 #{n.size - tot}"
> 
> The main difference seems to be using "count" instead of "each_byte". But why 
> is it 5-6x faster to "count" 9.times than "each_byte" only once?
> Or did i ignore anything?

The above code is pretty nice.. I didn't know about the
'count'-method. The reason this is faster, is because the 'big loop',
the scan over the string, is in this code done internally, in the C
implementation of the count method. The other code has the loop
explicitly in ruby-code, which is slower.

The difference however is that the above code does the scan over the
String several times (# of chars to check - 1) in C, while all the other
code scans the String only once in ruby.

Probably there is a trade-off... maybe if you would wanna count all
occurences of [a-zA-Z0-9], then you would have to do the
'count'-method 57 times (57 because the above code assumes that only
the characters you count appear in the String), effectively scanning
the String 57 times. This might be slower than scanning the String
only once in ruby-code. (didn't test this though...)

Ruben