CSC/ECE 517 Fall 2012/ch1 1w58 am
Ruby Blocks, Iterators, Functional Idioms
This wiki-page serves as a knowledge source for understanding Ruby Blocks, Iterators, Functional Idioms.
Introduction
Ruby has simplified the way programmers use loops and iterators. Ruby helps programmers to use DRY principle effectively by using blocks and defining iterators over collections. This helps in minimizing the development work that programmers often find in any other O-O style programming language. In ruby, these iterators, blocks and functional idioms are explained as:
Iterators are Collection defined methods that helps to iterate over all the elements present in a Collection. Ruby Collections are basically objects that store a group of data members of various types. Examples of Collection are arrays, hashes etc. A block consists of chunks of codes with a name assigned to it enclosed withing braces. For example,
my_block { puts "Hello World" }
Functional idioms are ... (please feel free to add about functional idioms here and become the author of it :) )
Iterators
Conventional Methods
Iterators in ruby can be written in following ways:
The times iterator:
The times iterators works similar to the for loop used in programming languages. As the name suggests it allows to loop over a chunk of code n number of times. For example:
5.times { puts "Hello Reviewers!" }
This code produces the following output:
Hello Reviewers! Hello Reviewers! Hello Reviewers! Hello Reviewers! Hello Reviewers!
Any chunk of code enclosed within the curly braces will execute 5 times in the above example.
The Upto iterator
The upto iterator is also similar to the for loop. However, the difference between times and upto iterator is that, upto allows the programmer to specify the start index m and the end index n of the loop. So, if we define an upto iterator as m.upto(n) { # do some work }, then the code in curly braces will be executed n - m + 1 number of times. For example:
m = 45 n = 48 m.utpo(n) {puts "Hello Reviewers! This is really cool, isn't it?"}
This code produces the following output:
Hello Reviewers! This is really cool, isn't it? Hello Reviewers! This is really cool, isn't it? Hello Reviewers! This is really cool, isn't it? Hello Reviewers! This is really cool, isn't it?
Here the loop will be executed 48 - 45 + 1 = 4 number of times. If we had used times than 45.times would have printed the puts statement 45 number of times. Hence it allows us to make loop execution dynamic as compared to the times iterator which is relatively static.