CSC/ECE 517 Fall 2012/ch1 1w58 am

From Expertiza_Wiki
Revision as of 06:01, 30 September 2012 by Aspalana (talk | contribs)
Jump to navigation Jump to search

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:

    1. 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.

      Topical References

      Further Reading