Search This Blog

Monday, August 13, 2012

Ruby - more concepts


Module:
Simple module implementation
Here both the module and main program is in same file. In almost all cases they won't be !! Modules are like libraries. You will be having it in separate file and including it whenever you require that functionality. To include a module you need to use 'require' keyword. 
require filename_with_correct_path
where filename is the file which contains the module you are including.

Arrays and Hashes:


Arrays,hashes and looping through them
Arrays -- same as arrays in other programming languages. Heterogeneous in nature.
Hash -- Key value pair. Key and values are separate arrays! Its also heterogeneous. 
The above program shows various ways of accessing contents of arrays and hashes. Output is given below.


Output of arrays hashes program
Looping techniques:
Looping techniques
For C programmers, Ruby's looping techniques may seem complex. But its not the fact. They are very simple and powerful once you get hold of it. Above program shows you various simple looping techniques applied commonly.

Collection,mapping and array initialization:

Collect,map and arrays
Collect and map are very similar, except the fact that collect returns an array while map returns enumerator. Initializing an array is also demonstrated and it can be painless unlike in C or C++. 
Output of collect,map
Class and inheritance:
Class,inheritance
@varname - varname is a instance variable => accessible through instance of class only
@@varname - varname is a class variable => accessible through class only using scope resolution operator
unless you specify accessor or write methods of your own inside class the instance variables remain inaccessible outside the class. 
class A < B =>class A is inheriting from class B => B is superclass of A
super calls the method of superclass having the same name as the method inside which super is used.
Output of class,inheritance
Blocks:
Simple code demonstrating the use of blocks

Output of the above block program

Proc and lambda:


Sample program demonstrating how proc and lambda work
The above program helps in understanding how to use proc and lambda. Using it in optimal way depends on programming logic of the user.
There are 2 main differences between lambda and proc. They are,
  1. Proc acts as inline function. So a return statement inside proc would mean returning from the calling function itself.A return inside lambda however returns control to the calling function
  2. A proc can work without throwing any error even if the number of arguments doesn't match. A lambda will throw an error saying wrong number of arguments.
In the code i have given above , remove the commented lines and try understanding the errors thrown for better understanding.

No comments:

Post a Comment