All possible ways of iterating

M

Mark Fayngersh

Hey,

I am just curious as to what are all the possible methods of iterating
through a code block in ruby.

Thanks.
 
M

Markus Roberts

I am just curious as to what are all the possible methods of
iterating through a code block in ruby.

Ruby it a Turing complete language. There are, literally, an infinite
number of ways to do it. (Consider continuations, for example...)

-- MarkusQ
 
B

Bertram Scharpf

Am Mittwoch, 02. Sep 2009, 09:20:06 +0900 schrieb Mark Fayngersh:
I am just curious as to what are all the possible methods of iterating
through a code block in ruby.

More than in APL.

Bertram
 
D

David Masover

I am just curious as to what are all the possible methods of iterating
through a code block in ruby.

The way I think of it is, you start with while/until and for, and while/until
can be used as a sort of 'do while' loop, too.

But normally, you wouldn't use these, you'd use something like

[1,2,3].each do |x|
# do something with x
end

Specifically, look up Enumerable, and blocks in general. I don't consider these
to be separate methods of iterating, since you could easily implement them
like this:

class Array
def each
if block_given?
for x in self
yield x
end
else
enum_for
end
end
end

So, the language is conceptually simpler -- there are at most five ways of
iterating, depending how you count (while, do-while, until, do-until, for).
But that's also not entirely honest, as things in the standard library are
often written in C for speed, even if they're _possible_ to write in Ruby.
Each is no exception.

So, to answer your question, there are very few ways that are built into the
language, though how many there are depends how you count. On the other hand,
there are an infinite number of ways you could define yourself. For example:

def twice
yield
yield
end

twice { puts 'hello' }
 
R

Robert Klemme

2009/9/2 Mark Fayngersh said:
I am just curious as to what are all the possible methods of iterating
through a code block in ruby.

You do not exactly "iterate through a code block". Instead, code
blocks are used for some of the iteration idioms in Ruby.

Btw, why do you ask?

robert
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top