Newb question

Why does this

p 3.times {|i| puts i}

produce

0
1
2
3

???

Try

p 2.times {|i| puts "Number:#{i}"}

u will see the last line is the returncode of i from the last loop

Rong schrieb:

···

Why does this

p 3.times {|i| puts i}

produce

0
1
2
3

???

--
Otto Software Partner GmbH

Jan Pilz (e-mail: Jan.Pilz@osp-dd.de)

Tel. 0351/49723202, Fax: 0351/49723119
01067 Dresden, Freiberger Straße 35 - AG Dresden, HRB 2475
Geschäftsführer: Burkhard Arrenberg, Heinz A. Bade, Jens Gruhl

The loop outputs 0, 1, and 2.

The 'p' outputs the value of the entire statement. The times method returns the value of its receiver, which is 3 in this case.

Regards

Dave

···

On Sep 8, 2008, at 12:53 AM, Rong wrote:

p 3.times {|i| puts i}

produce

0
1
2
3

try the following:

a = 3.times {|i| puts i}
puts "a = #{a}"

martin

···

On Sun, Sep 7, 2008 at 10:53 PM, Rong <ron.green@gmail.com> wrote:

Why does this

p 3.times {|i| puts i}

produce

0
1
2
3

Ron Green wrote:

Why does this

p 3.times {|i| puts i}

produce

0
1
2
3

???

I think that a way to see what they are saying more clearly is thus:

ar = Array.new
3.times {|i| ar << i}
p ar

=> [0, 1, 2]

It does things as expected but internally to the block it has that last
bit.

I hope that helps.

···

--
Posted via http://www.ruby-forum.com/\.

But why is it incrementing?

···

On Sep 8, 1:00 am, Dave Thomas <d...@pragprog.com> wrote:

On Sep 8, 2008, at 12:53 AM, Rong wrote:

> p 3.times {|i| puts i}

> produce

> 0
> 1
> 2
> 3

The loop outputs 0, 1, and 2.

The 'p' outputs the value of the entire statement. The times method
returns the value of its receiver, which is 3 in this case.

Regards

Dave

Because you asked it to?

ri Integer.times
---------------------------------------------------------- Integer#times
      int.times {|i| block } => int

···

On Sep 8, 2008, at 1:11 AM, Rong wrote:

But why is it incrementing?

------------------------------------------------------------------------
      Iterates block int times, passing in values from zero to int - 1.

         5.times do |i|
           print i, " "
         end

      produces:

         0 1 2 3 4

It's not. n.times {|i| ... } calls the block with values from 0 to
n-1, then returns n. The loop variable isn't incremented that one
final time, if that's what you were asking.

martin

···

On Sun, Sep 7, 2008 at 11:11 PM, Rong <ron.green@gmail.com> wrote:

But why is it incrementing?