--00032555441a5f5fe7047934b41e
Content-Type: text/plain; charset=ISO-8859-1

On Wed, Nov 25, 2009 at 9:01 AM, Ralph Shnelvar <ralphs / dos32.com> wrote:

> Is there a document or website that describes how Ruby works?
>
> For instance ...
>

You have the source.  That's often the best way to really understand how a
given implementation works.



> y> 1_000_000.times {|x| y+


>
> (1) Does the block get compiled a million times?
>

No.  The block's source is only evaluated once.  Different implementations
will represent it differently, but the end result is that the block becomes
an evaluated thing that will then be executed a million times.


> (2) What's the best Ruby way to do a sum from 1 to 1_000_000
>

Math is your friend.  The sum of a string of integers from 1 to n is:  (n**2
+ n)/2

def sum(n)
  (n**2 + n) / 2
end

However, in that code you wrote, you are actually summing the numbers from
zero to 999999.  Fixnum#times starts at 0.  You probably actually want
something like 1.upto(1000000).  Math is still the best way to do it,
though.

(3) Is there a difference in speed between IRB.exe and ruby.exe in
> executing the above code?
>

Not really.  irb is just a bunch of code to facilitate a sort of ruby
shell.  The code is all still be executed by Ruby, though.


> (4) In IRB, whats the best way to time the code, above?
>
>
Read up on the 'benchmark' library.  There are several ways to use it.

One way:

require 'benchmark'

Benchmark.bm {|bm| bm.report {y  ; 1000000.times {|n| y + }}}


Kirk Haines

--00032555441a5f5fe7047934b41e--