All possible ways of iterating

Hey,

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

Thanks.

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

More than in APL.

Bertram

···

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.

--
Bertram Scharpf
Stuttgart, Deutschland/Germany
http://www.bertram-scharpf.de

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' }

···

On Tuesday 01 September 2009 07:20:06 pm Mark Fayngersh wrote:

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

···

2009/9/2 Mark Fayngersh <phunny.phacts@gmail.com>:

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

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

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

We all praise the module Enumerable now.
It is a really great module.

http://www.ruby-doc.org/core/classes/Enumerable.html

···

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