Loops & Iterators in Ruby
Ruby provides the basic while and unless loops and iterators. Let us go through while and until first before looking at iterators.
A "while" loop defines that a statement or block of code is to be rerun time and time again while a condition remains true, and then execution is to continue after the statement or block. An "until" loop says that the block is to be performed until the condition goes true (i.e. while it is false).
Just like the "if" and "unless", "while" and "until" are written with an 'end' key-worded block, or as modified after a piece of code.
The method "each" when run on what we call a collection object will cause a block of code to be run on each of the elements of the collection object in turn. Yes, that's rather different to many other languages (though it does parallel foreach in PHP and for in Python).
You can write a loop that looks reasonably conventional to step up through a series of numbers - example coming up - but in addition you can write far clearer and more elegant loops to process all the members of a collection in turn, without having to refer to them by their position number all the time.
|All times are GMT +5.5. The time now is 15:24.|