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

???

Otto Software Partner GmbH

Jan P. (e-mail: [email protected])

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

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

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

But why is it incrementing?

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

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

But why is it incrementing?

On Sun, Sep 7, 2008 at 11:11 PM, Rong [email protected] wrote:

But why is it incrementing?

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

Ron G. 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.

On Sun, Sep 7, 2008 at 10:53 PM, Rong [email protected] wrote:

Why does this

p 3.times {|i| puts i}

produce

0
1
2
3

try the following:

a = 3.times {|i| puts i}
puts “a = #{a}”

martin