.times loop returns the number?

R

Roger Pack

12.times do |month_ahead|
end

returns 12
I would have expected this to return a collected array of the return
value of each block. Odd?
 
J

John Joyce

12.times do |month_ahead|
end

returns 12
I would have expected this to return a collected array of the return
value of each block. Odd?
Not odd at all.
x.times do |x|
code_here_using_x
end

In this iterating construct the current value passed in | | is the
current value of x.
other than that,
Ruby blocks always return the last value returned in the block.
if you simply do this:

x.times do |x|
code_here_using_x
puts "cat"
end

the block will return "cat"

The iterating constructs in Ruby are not always used to return a
value as in C-like languages.
They simply perform the code in the block a number of times.
This includes powerful and flexible concepts such iterating over
collections (arrays, hashes, etc...)

a = Array.new

a.each do |element|
some_function( element )
end

The main idea on iterators in ruby is the iterating!
But do keep in mind the simple convenience that Ruby code blocks
implicitly return the last value in the block.

a.each do |element|
some_function( element )
46
end

returns 46.
Sometimes that is useful and convenient.
 
R

Rick DeNatale

Ruby blocks always return the last value returned in the block.

true but..
if you simply do this:

x.times do |x|
code_here_using_x
puts "cat"
end

the block will return "cat"

But the whole expression won't.

irb(main):001:0> irb(main):001:0> 5.times {|i| "a"}
=> 5
irb(main):002:0> 5.times {|i| puts "cat"}
cat
cat
cat
cat
cat
=> 5

And puts "cat" doesn't return "cat"

irb(main):004:0> puts "cat"
cat
=> nil

On the other hand Integer#times is documented to return the integer:

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

Gary Wright

12.times do |month_ahead|
end

returns 12
I would have expected this to return a collected array of the return
value of each block. Odd?

To get a collected array:
=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]

Or via enumerators in Ruby 1.8:
=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]


Or via Ruby 1.9's new enumerator behavior:
=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22]


Gary Wright
 
S

Sebastian Hungerecker

ara.t.howard said:
i often define this

class Numeric
=A0 =A0def of &block
=A0 =A0 =A0Array.new(to_i).map &block
=A0 =A0end
end

Why not
Array.new(to_i, &block)
?

=2D-=20
Jabber: (e-mail address removed)
ICQ: 205544826
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top