Skip to main content

Posts

Showing posts with the label ruby on rails

Ruby on rails part 6 - Blocks , lambda, procs and closure

 Blocks , lambda, procs  and closure Table of content  1. Blocks 2. Lambda 3. Procs 4. Closure Blocks  Ruby blocks are little anonymous functions that can be passed into methods. Blocks are enclosed in a do-end statement or between brackets {} 
. Blocks can have multiple arguments
. The argument names are defined between two pipe | characters. Blocks are typically used with ‘each’ method which iterates over a list. Syntax of block using {} ['List of items'].each { | block arguments|  block body }  Syntax of block using do-end ['List of items'].each do | block arguments |      # block body end Example of block declared as do-end with each method.   [ 1 , 2 , 3 ].each do |num| puts num end     Output   $ ruby block_with_each.rb 1 2 3 $    Blocks can also be saved in variables or passed as argument to another function.   yield is a Ruby keyword that is used to call a block. When you use the yield ...

Ruby on Rails Part 4 - Exception Handling

  Ruby on Rails Part 4 - Exception Handling  Table of content Exception Handling retry raise ensure else  catch and throw Exception classes Exception Handling Enclose the code that could raise an exception with a begin/end block and use rescue clauses to tell Ruby the types of exceptions that you want to handle. The syntax for exception handling : 
 begin  
      #- statements
 rescue OneTypeOfException       #-
 handle the exception rescue AnotherTypeOfException       #- 
handle the exception else       
# Other exceptions
 ensure 
      # ensure block is always executed
 end 
 Everything from begin to rescue is protected 

in the block. 
If an exception occurs during the execution of this block of code, control is passed to the 

block between rescue and end.
 
For each rescue clause in the begin block, Ruby compares the raised Exception against each 

of the parameters of the...

Ruby on Rails Part 3 - Modules and mixins

 Ruby on Rails Part 3 - Modules and mixins Table of content Modules Inside a module method require vs include vs extend Mixins Accessing variable Class vs instance methods Modules A Module is a collection of methods, constants, and class variables. Modules are defined as a class, but with the module keyword instead of class keyword. The name of a module must start with a capital letter. You cannot inherit modules using the <  i.e. you cannot create a subclass of a module. You cannot create an objects of a module.
 Modules are used for namespaces and as mixins.
 All the classes are modules, but all the modules are not classes.  A class can use namespaces, but they cannot use mixins like modules. The syntax for declaring a module is : module Module_name 
      # statements to be executed end      module ModuleName # Create a module C = 10 ; # Module constant # Method name must be preceded by the module name, this is a module me...