SlideShare una empresa de Scribd logo
1 de 17
Descargar para leer sin conexión
RUBY BLOCKS, LOOPS/ITERATORS
            & FLOW CONTROLS
●   Ruby blocks
●   Ruby yield
●   Block, proc and lambda
●   Iterators: ruby-loops
●   Flow controls
Ruby blocks:
○   Block consists of a chunk of code
○   We assign a name to block
○   Code inside a block is always enclosed within {} braces or do-
    end.
○   A block can always be invoked from a function with same name
    as the block. E.g. a block has name ‘check’ then it can be
    invoked from a method named ‘check’.
○   We can invoke a block with using ‘yield’ statement.
○   We can pass parameters to block as well.
○   Real-time examples of block are array collect, select, map
    within which can simply attach a block of code and process that
    code on array, times loop i.e. 5.times do |a| …end.
#example1
def test
      puts “we are in method”
      yield
      puts “we are in method”
      yield
End
Test { puts “we are in block”}
>>> result will be :
You are in the method
You are in the block
You are again back to the method
You are in the block

#example2
10.times {|a| puts a }
Block, Proc, Lambda & methods:
○   Blocks, procs and lamdba are one of the most powerful aspects of ruby,
    and also one of the most misunderstood too.
○   This can be because ruby handles CLOSURES in a bit different/unique
    way. To make it more difficult its has four different ways of handling
    closures.
○   Block: most common, easiest and arguably most “ruby like” way to use
    closures in ruby.
○   Procedures AKA Procs: blocks are good, but we cant reuse them,
    whenever we need we have to rewrite them. There comes Procs. Procs
    are nothing more than a block that can be reused.
○   Lambda: lambda is almost similar to Procs except two subtle
    differences,
     ○ unlike Procs, lambdas check the number of arguments passed and returns
       error if not.
     ○ lambdas have diminutive returns.
○   Method: when we already have some method and want to pass it to
    another method as a closure, we use ‘method’ method provided by ruby
    to keep things DRY.
How Proc works?
class Array
 def iterate!(code)
   self.each_with_index do |n, i|
     self[i] = code.call(n)
   end
 end
end
array_1 = [1, 2, 3, 4]
array_2 = [2, 3, 4, 5]              #example2
                                    def callbacks(procs) procs[:
square = Proc.new do |n|
                                    starting].call
     n ** 2                              puts "Still going" procs[:
end                                 finishing].call
array_1.iterate!(square)            end
array_2.iterate!(square)
                                    callbacks(:starting => Proc.new { puts
                                    "Starting" }, :finishing => Proc.new {
                                    puts "Finishing" })
Lambda: an example, how its different from Proc:
#example1
def args(code)
     one, two = 1, 2
     code.call(one, two)
end
args(Proc.new{|a, b, c|
     puts "Give me a #{a} and a #{b} and a #{c.class}”
})
args(lambda{|a, b, c|
     puts "Give me a #{a} and a #{b} and a #{c.class}”
})


#example2
def lambda_return
      lambda { return "lambda" }.call
      return "lambda_return method finished"
End
puts lambda_return
#=> lambda_return method finished
‘method’ ruby method:

class Array
 def iterate!(code)
    self.each_with_index do |n, i|
     self[i] = code.call(n)
    end
  end
end
def square(n)
   n ** 2
end
array = [1, 2, 3, 4]
array.iterate!(method(:square))
Yield???

○   Placeholder for any code-block i.e. block, proc or lambda.
○   Yield lets us branch from within a method and execute some external
    code, then return to the original code in the first method.
○   Blind date??
     def block1
          puts "Start of block1..."
          yield
          yield
          puts "End of block1."
     end
     block1 {puts "yielding...”}
○   we can wrap yield with if statement as well like
     yield if block_given?
○   block_given? What is this?
Ruby Iterators: looping
Ruby Loops/Iterators:

●   Loops/Iterators in Ruby are used to execute the same block of code a
    specified number of times.
●   In ruby, for better understanding, we can assume to classify
    looping/iterating in 2 buckets:
     ●   Simple way to loop/iterate.
     ●   Complex way to loop/iterate.
●   Common Looping ways we use in ruby are for, while, loop, until,
    while/until modifiers etc.
●   Common iterating ways we use in ruby are each iterators, time iterators,
    upto & step iterators, each_index iterators.
Ruby Looping Constructs:

○   Loop: The simplest looping constructs in ruby is ‘loop’ method.
    Technically it’s an iterating block as it takes a block as input.
○   While: The while loop in Ruby is just like the standard while loop in any
    other language nothing too fancy.
○   Until: The until loop is similar to the while loop but the logic is reversed.
○   While/until modifiers: Ruby also allows you to use the while and until
    keywords as modifiers, which means you can put them at the end of an
    expression just like you can do with the if statement.
○   For: If we discount the loop method then the for loop acts as a kind of
    bridge between looping constructs and iterators in Ruby. The for loop is
    still a looping construct but it acts almost like an iterator without actually
    taking a block.
#example1-loop
loop {puts "HELLO"}
                                           #example2-while
i=0
                                           i=1
loop do
                                           while i < 11
    i+=1 print "#{i} "
                                               puts i
break if i==10
                                               i+=1
end
                                           end

   #example3-until          #example4-while/until modifiers
   i=1                      i=0
   until I > 10             puts I while i < 10
        puts i
        i+=1                i=0
   end                      Puts i until I == 10

           #example5-for
           i=1
           for i in 1..10
                 puts i
           end
Ruby Iterators:

○   Iterators are methods that take blocks and execute that block as many
    times as there are iterations.
○   Each iterators(something.each do ... end)
    ○   Iterates through each elements.
○   Times iterators(x.times do … end)
    ○   The times iterator is similar to you classic for loop in other languages and
        will allow you to execute a loop and perform an action (according to the
        block you write) x number of time
○   Upto and step iterators
    ○   This is also similar to for loop too, that we execute from number x up to
        number y.
    ○   Step iterators helps to skip few steps between.
‘Each’ Iterators:

array = [1,2,3,4,5,6,7,8,9,10]
array.each {|value| print "#{value} "}

(1..5).each { puts ‘We are here!’ }

(1…5).each { puts ‘we are here’}



****
Also, for does not exactly qualify as a syntax sugar for each, because they
handle the scoping of new variables differently: each makes them
disappear outside the block, whereas for makes them persist. With
experience you’re likely to find you want new variables to be confined to
the block, making each the better choice.
Control Flows:

○   Ruby offers conditional structures that are pretty common to modern
    languages.
○   If statement.
○   If-else statement.
○   If modifier statement.
○   Unless statement.
○   Unless modifier.
○   Case statement.
     case expr0
         when expr1, expr2
            stmt1
         when expr3, expr4
            stmt2
         else
            stmt3
     end
QUESTIONS???

Más contenido relacionado

La actualidad más candente

Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Railselliando dias
 
Introduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transformsIntroduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transformsMarcin Grzejszczak
 
Learning groovy 1: half day workshop
Learning groovy 1: half day workshopLearning groovy 1: half day workshop
Learning groovy 1: half day workshopAdam Davis
 
QTP VB Script Trainings
QTP VB Script TrainingsQTP VB Script Trainings
QTP VB Script TrainingsAli Imran
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)HamletDRC
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programmingRodolfo Finochietti
 
Ruby - a pure object oriented language
Ruby  - a pure object oriented languageRuby  - a pure object oriented language
Ruby - a pure object oriented languagePetru Cioată
 
7400354 vbscript-in-qtp
7400354 vbscript-in-qtp7400354 vbscript-in-qtp
7400354 vbscript-in-qtpBharath003
 
Basic vbscript for qtp
Basic vbscript for qtpBasic vbscript for qtp
Basic vbscript for qtpCuong Tran Van
 
Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]srikanthbkm
 
CMP1001 Loops 1
CMP1001 Loops 1CMP1001 Loops 1
CMP1001 Loops 1steves2001
 

La actualidad más candente (20)

Clojure for Rubyists
Clojure for RubyistsClojure for Rubyists
Clojure for Rubyists
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
Introduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transformsIntroduction to Groovy runtime metaprogramming and AST transforms
Introduction to Groovy runtime metaprogramming and AST transforms
 
Ast transformation
Ast transformationAst transformation
Ast transformation
 
How to write Ruby extensions with Crystal
How to write Ruby extensions with CrystalHow to write Ruby extensions with Crystal
How to write Ruby extensions with Crystal
 
Php training in chandigarh
Php  training in chandigarhPhp  training in chandigarh
Php training in chandigarh
 
Learning groovy 1: half day workshop
Learning groovy 1: half day workshopLearning groovy 1: half day workshop
Learning groovy 1: half day workshop
 
Briefly Rust
Briefly RustBriefly Rust
Briefly Rust
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Ruby
RubyRuby
Ruby
 
QTP VB Script Trainings
QTP VB Script TrainingsQTP VB Script Trainings
QTP VB Script Trainings
 
VB Script
VB ScriptVB Script
VB Script
 
Os Goodger
Os GoodgerOs Goodger
Os Goodger
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
 
Ruby - a pure object oriented language
Ruby  - a pure object oriented languageRuby  - a pure object oriented language
Ruby - a pure object oriented language
 
7400354 vbscript-in-qtp
7400354 vbscript-in-qtp7400354 vbscript-in-qtp
7400354 vbscript-in-qtp
 
Basic vbscript for qtp
Basic vbscript for qtpBasic vbscript for qtp
Basic vbscript for qtp
 
Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]
 
CMP1001 Loops 1
CMP1001 Loops 1CMP1001 Loops 1
CMP1001 Loops 1
 

Similar a Blocks and loops.pptx

Ruby basics ||
Ruby basics ||Ruby basics ||
Ruby basics ||datt30
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n2
name name2 n2name name2 n2
name name2 n2callroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.pptcallroom
 
Ruby for Perl Programmers
Ruby for Perl ProgrammersRuby for Perl Programmers
Ruby for Perl Programmersamiable_indian
 

Similar a Blocks and loops.pptx (20)

Ruby basics
Ruby basicsRuby basics
Ruby basics
 
10 ruby loops
10 ruby loops10 ruby loops
10 ruby loops
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Ruby basics ||
Ruby basics ||Ruby basics ||
Ruby basics ||
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
test ppt
test ppttest ppt
test ppt
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt21
ppt21ppt21
ppt21
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt17
ppt17ppt17
ppt17
 
ppt30
ppt30ppt30
ppt30
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.ppt
 
ppt18
ppt18ppt18
ppt18
 
Ruby for Perl Programmers
Ruby for Perl ProgrammersRuby for Perl Programmers
Ruby for Perl Programmers
 
ppt9
ppt9ppt9
ppt9
 

Último

AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 

Último (20)

AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 

Blocks and loops.pptx

  • 2. Ruby blocks ● Ruby yield ● Block, proc and lambda ● Iterators: ruby-loops ● Flow controls
  • 3. Ruby blocks: ○ Block consists of a chunk of code ○ We assign a name to block ○ Code inside a block is always enclosed within {} braces or do- end. ○ A block can always be invoked from a function with same name as the block. E.g. a block has name ‘check’ then it can be invoked from a method named ‘check’. ○ We can invoke a block with using ‘yield’ statement. ○ We can pass parameters to block as well. ○ Real-time examples of block are array collect, select, map within which can simply attach a block of code and process that code on array, times loop i.e. 5.times do |a| …end.
  • 4. #example1 def test puts “we are in method” yield puts “we are in method” yield End Test { puts “we are in block”} >>> result will be : You are in the method You are in the block You are again back to the method You are in the block #example2 10.times {|a| puts a }
  • 5. Block, Proc, Lambda & methods: ○ Blocks, procs and lamdba are one of the most powerful aspects of ruby, and also one of the most misunderstood too. ○ This can be because ruby handles CLOSURES in a bit different/unique way. To make it more difficult its has four different ways of handling closures. ○ Block: most common, easiest and arguably most “ruby like” way to use closures in ruby. ○ Procedures AKA Procs: blocks are good, but we cant reuse them, whenever we need we have to rewrite them. There comes Procs. Procs are nothing more than a block that can be reused. ○ Lambda: lambda is almost similar to Procs except two subtle differences, ○ unlike Procs, lambdas check the number of arguments passed and returns error if not. ○ lambdas have diminutive returns. ○ Method: when we already have some method and want to pass it to another method as a closure, we use ‘method’ method provided by ruby to keep things DRY.
  • 6. How Proc works? class Array def iterate!(code) self.each_with_index do |n, i| self[i] = code.call(n) end end end array_1 = [1, 2, 3, 4] array_2 = [2, 3, 4, 5] #example2 def callbacks(procs) procs[: square = Proc.new do |n| starting].call n ** 2 puts "Still going" procs[: end finishing].call array_1.iterate!(square) end array_2.iterate!(square) callbacks(:starting => Proc.new { puts "Starting" }, :finishing => Proc.new { puts "Finishing" })
  • 7. Lambda: an example, how its different from Proc: #example1 def args(code) one, two = 1, 2 code.call(one, two) end args(Proc.new{|a, b, c| puts "Give me a #{a} and a #{b} and a #{c.class}” }) args(lambda{|a, b, c| puts "Give me a #{a} and a #{b} and a #{c.class}” }) #example2 def lambda_return lambda { return "lambda" }.call return "lambda_return method finished" End puts lambda_return #=> lambda_return method finished
  • 8. ‘method’ ruby method: class Array def iterate!(code) self.each_with_index do |n, i| self[i] = code.call(n) end end end def square(n) n ** 2 end array = [1, 2, 3, 4] array.iterate!(method(:square))
  • 9. Yield??? ○ Placeholder for any code-block i.e. block, proc or lambda. ○ Yield lets us branch from within a method and execute some external code, then return to the original code in the first method. ○ Blind date?? def block1 puts "Start of block1..." yield yield puts "End of block1." end block1 {puts "yielding...”} ○ we can wrap yield with if statement as well like yield if block_given? ○ block_given? What is this?
  • 11. Ruby Loops/Iterators: ● Loops/Iterators in Ruby are used to execute the same block of code a specified number of times. ● In ruby, for better understanding, we can assume to classify looping/iterating in 2 buckets: ● Simple way to loop/iterate. ● Complex way to loop/iterate. ● Common Looping ways we use in ruby are for, while, loop, until, while/until modifiers etc. ● Common iterating ways we use in ruby are each iterators, time iterators, upto & step iterators, each_index iterators.
  • 12. Ruby Looping Constructs: ○ Loop: The simplest looping constructs in ruby is ‘loop’ method. Technically it’s an iterating block as it takes a block as input. ○ While: The while loop in Ruby is just like the standard while loop in any other language nothing too fancy. ○ Until: The until loop is similar to the while loop but the logic is reversed. ○ While/until modifiers: Ruby also allows you to use the while and until keywords as modifiers, which means you can put them at the end of an expression just like you can do with the if statement. ○ For: If we discount the loop method then the for loop acts as a kind of bridge between looping constructs and iterators in Ruby. The for loop is still a looping construct but it acts almost like an iterator without actually taking a block.
  • 13. #example1-loop loop {puts "HELLO"} #example2-while i=0 i=1 loop do while i < 11 i+=1 print "#{i} " puts i break if i==10 i+=1 end end #example3-until #example4-while/until modifiers i=1 i=0 until I > 10 puts I while i < 10 puts i i+=1 i=0 end Puts i until I == 10 #example5-for i=1 for i in 1..10 puts i end
  • 14. Ruby Iterators: ○ Iterators are methods that take blocks and execute that block as many times as there are iterations. ○ Each iterators(something.each do ... end) ○ Iterates through each elements. ○ Times iterators(x.times do … end) ○ The times iterator is similar to you classic for loop in other languages and will allow you to execute a loop and perform an action (according to the block you write) x number of time ○ Upto and step iterators ○ This is also similar to for loop too, that we execute from number x up to number y. ○ Step iterators helps to skip few steps between.
  • 15. ‘Each’ Iterators: array = [1,2,3,4,5,6,7,8,9,10] array.each {|value| print "#{value} "} (1..5).each { puts ‘We are here!’ } (1…5).each { puts ‘we are here’} **** Also, for does not exactly qualify as a syntax sugar for each, because they handle the scoping of new variables differently: each makes them disappear outside the block, whereas for makes them persist. With experience you’re likely to find you want new variables to be confined to the block, making each the better choice.
  • 16. Control Flows: ○ Ruby offers conditional structures that are pretty common to modern languages. ○ If statement. ○ If-else statement. ○ If modifier statement. ○ Unless statement. ○ Unless modifier. ○ Case statement. case expr0 when expr1, expr2 stmt1 when expr3, expr4 stmt2 else stmt3 end