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.

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