SlideShare a Scribd company logo
1 of 20
Download to read offline
Blocks



2011   8   25
Outline

                • Basics	
  of	
  blocks
                • Scopes,	
  carry	
  variables	
  through	
  scopes
                • Manipulate	
  scopes	
  	
  using	
  instance_eval(	
  )
                • Convert	
  blocks	
  to	
  callable	
  objects
                • A	
  DSL	
  example

2011   8   25
Definition
                • Definition of blocks
                    • Multi-lines
                          do ... end
                     • Single line
                          Curly braces {}



2011   8   25
Features
                def a_method(a, b)
                  a + yield(a, b)
                end

                a_method(1,2){|x,y|(x+y)*3} #=>10



                • Defined when calling a method
                • Block is passed to method
                • Method can call block using yield
                • Blocks can have arguments
                • Block can return values
2011   8   25
Using C#->Ruby
                 module Kernel
                   def using(resource)
                       begin
                         yield
                       ensure    # Ensure the dispose to be called
                         resource.dispose
                       end
                   end
                 end




                The exception of block called by ‘yield’ can be
                always captured by ‘ensure’

2011   8   25
Closures
                Bindings: Local variables, instance variables, self

                  def my_method
                   x = "Goodbye"
                   yield("cruel" )
                  end
                  x = "Hello"
                  my_method {|y| "#{x}, #{y} world" }
                  # => ?




2011   8   25
Using
                 def my_method
                   x = "Goodbye"
                   yield("cruel" )
                 end
                 x = "Hello"
                 my_method {|y| "#{x}, #{y} world" }
                 # => "Hello, cruel world"




                Block definition -> find x variables -> take x to
                method

2011   8   25
Block local variables
                def my_method
                yield
                end
                top_level_variable = 1
                my_method do
                 top_level_variable += 1
                 local_to_block = 1
                end


                top_level_variable # => ?
                local_to_block	 # => ?




2011   8   25
Block local variables
                def my_method
                yield
                end
                top_level_variable = 1
                my_method do
                 top_level_variable += 1
                 local_to_block = 1
                end


                top_level_variable # => 2
                local_to_block	 # => Error!




2011   8   25
Scope gates
                v1 = 1
                class MyClass
                 v2 = 2
                 local_variables
                  def my_method
                      v3 = 3
                      local_variables
                 end
                  local_variables
                end
                obj = MyClass.new
                obj.my_method
                obj.my_method
                local_variables


2011   8   25
Scope gates
                v1 = 1
                class MyClass    # SCOPE GATE: entering class
                 v2 = 2          # => ["v2"]
                 local_variables
                  def my_method # SCOPE GATE: entering def
                      v3 = 3
                      local_variables
                 end              # SCOPE GATE: leaving def
                  local_variables       # => ["v2"]
                end              # SCOPE GATE: leaving class
                obj = MyClass.new
                obj.my_method # => [:v3]
                obj.my_method # => [:v3]
                local_variables # => [:v1, :obj]


2011   8   25
Beyond scopes
                •   Global variables
                    • $var
                •   Top-level Instance variables
                    • @var
                • Scope wrap-up
                   • Class.new
                   • Module.new
                   • define_methods
2011   8   25
Example
                my_var = "Success"
                MyClass = Class.new do
                  puts "#{my_var} in the class definition!"
                  define_method :my_method do
                      puts "#{my_var} in the method!"
                  end
                end
                MyClass.new.my_method
                # => Success in the class definition!
                # => Success in the method!




2011   8   25
Instance_eval()
                class MyClass
                def initialize
                  @v = 1
                 end
                end
                obj = MyClass.new
                obj.instance_eval do
                 self   	 # => #<MyClass:0x3340dc @v=1>
                 @v	       # => 1
                end
                v=2
                obj.instance_eval { @v = v }
                obj.instance_eval { @v } # => 2 (passed to the block)



2011   8   25
Instance_eval()
                class CleanRoom
                def complex_calculation
                      # ...
                 end
                 def do_something
                      # ...
                 end
                end
                clean_room = CleanRoom.new
                 clean_room.instance_eval do
                      if complex_calculation > 10 do_something
                 end
                end



2011   8   25
Callable objects
                Call blocks by change it to object using proc or lambda,
                A Proc is a block that has been turned into an object.

                Proc:
                inc = Proc.new {|x| x + 1 }
                inc.call(2) # => 3

                Lambda:
                dec = lambda {|x| x - 1 }
                dec.class # => Proc
                dec.call(2) # => 1




2011   8   25
Procs VS Lambdas
                • Procs created with lambda( ) -> lambdas
                • Return
                   • return in lambda is more like method,
                     while return in procs return from scope
                     (defined in the scope)
                • Arity
                   • lambdas failed with wrong arguments but
                     proc is ok

2011   8   25
methods
                class MyClass
                  def initialize(value)
                    @x = value
                  end
                  def my_method
                    @x
                  end
                end
                object = MyClass.new(1)
                m = object.method :my_method
                m.call

                a lambda is evaluated in the scope
                Method is evaluated in the scope of its object




2011   8   25
Callable object wrap-up
                Blocks: Evaluated in the scope in which they’re defined.

                Procs: Objects of class Proc. Like blocks, they are
                evaluated in the scope where they’re defined.

                Lambdas: Also objects of class Proc but subtly different
                from regular proc.

                Methods: Bound to an object, they are evaluated in that
                object’s scope. They can also be unbound from their
                scope and rebound to the scope of another object.




2011   8   25
DSL

                • DSL for individual event
                • Shared among events
                • Adding setup instruction
                • Using & operator to pass setup
                • Not using global variables

2011   8   25

More Related Content

What's hot

Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Fwdays
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingRenas Rekany
 
Virtual base class
Virtual base classVirtual base class
Virtual base classTech_MX
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceOUM SAOKOSAL
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Pythonkwatch
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4mohamedsamyali
 
object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++Mohamad Al_hsan
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3mohamedsamyali
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsFALLEE31188
 

What's hot (20)

Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"Alexander Makarov "Let’s talk about code"
Alexander Makarov "Let’s talk about code"
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Delegate
DelegateDelegate
Delegate
 
Virtual base class
Virtual base classVirtual base class
Virtual base class
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
 
06 inheritance
06 inheritance06 inheritance
06 inheritance
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Python
 
Dart
DartDart
Dart
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
Inheritance
InheritanceInheritance
Inheritance
 
Class and object
Class and objectClass and object
Class and object
 
object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 

Similar to block

Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in RubyConFoo
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogrammingjoshbuddy
 
Model Manipulation Using Embedded DSLs in Scala
Model Manipulation Using Embedded DSLs in ScalaModel Manipulation Using Embedded DSLs in Scala
Model Manipulation Using Embedded DSLs in ScalaFilip Krikava
 
Metaprogramming code-that-writes-code
Metaprogramming code-that-writes-codeMetaprogramming code-that-writes-code
Metaprogramming code-that-writes-codeorga shih
 
Removing Methods (MOTM 2010.01)
Removing Methods (MOTM 2010.01)Removing Methods (MOTM 2010.01)
Removing Methods (MOTM 2010.01)Kevin Munc
 
Learn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueLearn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueJames Thompson
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby MetaprogrammingNando Vieira
 
Pharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkPharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkSerge Stinckwich
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the BasicsMichael Koby
 
JRuby 9000 - Optimizing Above the JVM
JRuby 9000 - Optimizing Above the JVMJRuby 9000 - Optimizing Above the JVM
JRuby 9000 - Optimizing Above the JVMCharles Nutter
 
Introduction to ruby eval
Introduction to ruby evalIntroduction to ruby eval
Introduction to ruby evalNiranjan Sarade
 
Real world cross-platform testing
Real world cross-platform testingReal world cross-platform testing
Real world cross-platform testingPeter Edwards
 
System Verilog 2009 & 2012 enhancements
System Verilog 2009 & 2012 enhancementsSystem Verilog 2009 & 2012 enhancements
System Verilog 2009 & 2012 enhancementsSubash John
 
Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013rivierarb
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introductionGonçalo Silva
 
Rails3ハンズオン資料
Rails3ハンズオン資料Rails3ハンズオン資料
Rails3ハンズオン資料Shinsaku Chikura
 

Similar to block (20)

Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
Why I choosed Ruby
Why I choosed RubyWhy I choosed Ruby
Why I choosed Ruby
 
Ruby Blocks
Ruby BlocksRuby Blocks
Ruby Blocks
 
Model Manipulation Using Embedded DSLs in Scala
Model Manipulation Using Embedded DSLs in ScalaModel Manipulation Using Embedded DSLs in Scala
Model Manipulation Using Embedded DSLs in Scala
 
Metaprogramming code-that-writes-code
Metaprogramming code-that-writes-codeMetaprogramming code-that-writes-code
Metaprogramming code-that-writes-code
 
Removing Methods (MOTM 2010.01)
Removing Methods (MOTM 2010.01)Removing Methods (MOTM 2010.01)
Removing Methods (MOTM 2010.01)
 
Learn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueLearn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a Rescue
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 
Pharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source SmalltalkPharo, an innovative and open-source Smalltalk
Pharo, an innovative and open-source Smalltalk
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the Basics
 
JRuby 9000 - Optimizing Above the JVM
JRuby 9000 - Optimizing Above the JVMJRuby 9000 - Optimizing Above the JVM
JRuby 9000 - Optimizing Above the JVM
 
Introduction to ruby eval
Introduction to ruby evalIntroduction to ruby eval
Introduction to ruby eval
 
Real world cross-platform testing
Real world cross-platform testingReal world cross-platform testing
Real world cross-platform testing
 
From dot net_to_rails
From dot net_to_railsFrom dot net_to_rails
From dot net_to_rails
 
System Verilog 2009 & 2012 enhancements
System Verilog 2009 & 2012 enhancementsSystem Verilog 2009 & 2012 enhancements
System Verilog 2009 & 2012 enhancements
 
Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
How to fake_properly
How to fake_properlyHow to fake_properly
How to fake_properly
 
Rails3ハンズオン資料
Rails3ハンズオン資料Rails3ハンズオン資料
Rails3ハンズオン資料
 

Recently uploaded

VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒anilsa9823
 
A305_A2_file_Batkhuu progress report.pdf
A305_A2_file_Batkhuu progress report.pdfA305_A2_file_Batkhuu progress report.pdf
A305_A2_file_Batkhuu progress report.pdftbatkhuu1
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesDipal Arora
 
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableCall Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableDipal Arora
 
Monthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxMonthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxAndy Lambert
 
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyThe Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyEthan lee
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Dave Litwiller
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsP&CO
 
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876dlhescort
 
Understanding the Pakistan Budgeting Process: Basics and Key Insights
Understanding the Pakistan Budgeting Process: Basics and Key InsightsUnderstanding the Pakistan Budgeting Process: Basics and Key Insights
Understanding the Pakistan Budgeting Process: Basics and Key Insightsseri bangash
 
Grateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdfGrateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdfPaul Menig
 
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Delhi Call girls
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...lizamodels9
 
9599632723 Top Call Girls in Delhi at your Door Step Available 24x7 Delhi
9599632723 Top Call Girls in Delhi at your Door Step Available 24x7 Delhi9599632723 Top Call Girls in Delhi at your Door Step Available 24x7 Delhi
9599632723 Top Call Girls in Delhi at your Door Step Available 24x7 DelhiCall Girls in Delhi
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Servicediscovermytutordmt
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayNZSG
 
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...Aggregage
 
Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Serviceritikaroy0888
 
Best Basmati Rice Manufacturers in India
Best Basmati Rice Manufacturers in IndiaBest Basmati Rice Manufacturers in India
Best Basmati Rice Manufacturers in IndiaShree Krishna Exports
 
HONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael HawkinsHONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael HawkinsMichael W. Hawkins
 

Recently uploaded (20)

VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒VIP Call Girls In Saharaganj ( Lucknow  ) 🔝 8923113531 🔝  Cash Payment (COD) 👒
VIP Call Girls In Saharaganj ( Lucknow ) 🔝 8923113531 🔝 Cash Payment (COD) 👒
 
A305_A2_file_Batkhuu progress report.pdf
A305_A2_file_Batkhuu progress report.pdfA305_A2_file_Batkhuu progress report.pdf
A305_A2_file_Batkhuu progress report.pdf
 
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best ServicesMysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
Mysore Call Girls 8617370543 WhatsApp Number 24x7 Best Services
 
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service AvailableCall Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
Call Girls Pune Just Call 9907093804 Top Class Call Girl Service Available
 
Monthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptxMonthly Social Media Update April 2024 pptx.pptx
Monthly Social Media Update April 2024 pptx.pptx
 
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case studyThe Coffee Bean & Tea Leaf(CBTL), Business strategy case study
The Coffee Bean & Tea Leaf(CBTL), Business strategy case study
 
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
Enhancing and Restoring Safety & Quality Cultures - Dave Litwiller - May 2024...
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and pains
 
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
 
Understanding the Pakistan Budgeting Process: Basics and Key Insights
Understanding the Pakistan Budgeting Process: Basics and Key InsightsUnderstanding the Pakistan Budgeting Process: Basics and Key Insights
Understanding the Pakistan Budgeting Process: Basics and Key Insights
 
Grateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdfGrateful 7 speech thanking everyone that has helped.pdf
Grateful 7 speech thanking everyone that has helped.pdf
 
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
Best VIP Call Girls Noida Sector 40 Call Me: 8448380779
 
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
Call Girls In DLf Gurgaon ➥99902@11544 ( Best price)100% Genuine Escort In 24...
 
9599632723 Top Call Girls in Delhi at your Door Step Available 24x7 Delhi
9599632723 Top Call Girls in Delhi at your Door Step Available 24x7 Delhi9599632723 Top Call Girls in Delhi at your Door Step Available 24x7 Delhi
9599632723 Top Call Girls in Delhi at your Door Step Available 24x7 Delhi
 
Call Girls in Gomti Nagar - 7388211116 - With room Service
Call Girls in Gomti Nagar - 7388211116  - With room ServiceCall Girls in Gomti Nagar - 7388211116  - With room Service
Call Girls in Gomti Nagar - 7388211116 - With room Service
 
It will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 MayIt will be International Nurses' Day on 12 May
It will be International Nurses' Day on 12 May
 
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
 
Call Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine ServiceCall Girls In Panjim North Goa 9971646499 Genuine Service
Call Girls In Panjim North Goa 9971646499 Genuine Service
 
Best Basmati Rice Manufacturers in India
Best Basmati Rice Manufacturers in IndiaBest Basmati Rice Manufacturers in India
Best Basmati Rice Manufacturers in India
 
HONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael HawkinsHONOR Veterans Event Keynote by Michael Hawkins
HONOR Veterans Event Keynote by Michael Hawkins
 

block

  • 1. Blocks 2011 8 25
  • 2. Outline • Basics  of  blocks • Scopes,  carry  variables  through  scopes • Manipulate  scopes    using  instance_eval(  ) • Convert  blocks  to  callable  objects • A  DSL  example 2011 8 25
  • 3. Definition • Definition of blocks • Multi-lines do ... end • Single line Curly braces {} 2011 8 25
  • 4. Features def a_method(a, b) a + yield(a, b) end a_method(1,2){|x,y|(x+y)*3} #=>10 • Defined when calling a method • Block is passed to method • Method can call block using yield • Blocks can have arguments • Block can return values 2011 8 25
  • 5. Using C#->Ruby module Kernel def using(resource) begin yield ensure # Ensure the dispose to be called resource.dispose end end end The exception of block called by ‘yield’ can be always captured by ‘ensure’ 2011 8 25
  • 6. Closures Bindings: Local variables, instance variables, self def my_method x = "Goodbye" yield("cruel" ) end x = "Hello" my_method {|y| "#{x}, #{y} world" } # => ? 2011 8 25
  • 7. Using def my_method x = "Goodbye" yield("cruel" ) end x = "Hello" my_method {|y| "#{x}, #{y} world" } # => "Hello, cruel world" Block definition -> find x variables -> take x to method 2011 8 25
  • 8. Block local variables def my_method yield end top_level_variable = 1 my_method do top_level_variable += 1 local_to_block = 1 end top_level_variable # => ? local_to_block # => ? 2011 8 25
  • 9. Block local variables def my_method yield end top_level_variable = 1 my_method do top_level_variable += 1 local_to_block = 1 end top_level_variable # => 2 local_to_block # => Error! 2011 8 25
  • 10. Scope gates v1 = 1 class MyClass v2 = 2 local_variables def my_method v3 = 3 local_variables end local_variables end obj = MyClass.new obj.my_method obj.my_method local_variables 2011 8 25
  • 11. Scope gates v1 = 1 class MyClass # SCOPE GATE: entering class v2 = 2 # => ["v2"] local_variables def my_method # SCOPE GATE: entering def v3 = 3 local_variables end # SCOPE GATE: leaving def local_variables # => ["v2"] end # SCOPE GATE: leaving class obj = MyClass.new obj.my_method # => [:v3] obj.my_method # => [:v3] local_variables # => [:v1, :obj] 2011 8 25
  • 12. Beyond scopes • Global variables • $var • Top-level Instance variables • @var • Scope wrap-up • Class.new • Module.new • define_methods 2011 8 25
  • 13. Example my_var = "Success" MyClass = Class.new do puts "#{my_var} in the class definition!" define_method :my_method do puts "#{my_var} in the method!" end end MyClass.new.my_method # => Success in the class definition! # => Success in the method! 2011 8 25
  • 14. Instance_eval() class MyClass def initialize @v = 1 end end obj = MyClass.new obj.instance_eval do self # => #<MyClass:0x3340dc @v=1> @v # => 1 end v=2 obj.instance_eval { @v = v } obj.instance_eval { @v } # => 2 (passed to the block) 2011 8 25
  • 15. Instance_eval() class CleanRoom def complex_calculation # ... end def do_something # ... end end clean_room = CleanRoom.new clean_room.instance_eval do if complex_calculation > 10 do_something end end 2011 8 25
  • 16. Callable objects Call blocks by change it to object using proc or lambda, A Proc is a block that has been turned into an object. Proc: inc = Proc.new {|x| x + 1 } inc.call(2) # => 3 Lambda: dec = lambda {|x| x - 1 } dec.class # => Proc dec.call(2) # => 1 2011 8 25
  • 17. Procs VS Lambdas • Procs created with lambda( ) -> lambdas • Return • return in lambda is more like method, while return in procs return from scope (defined in the scope) • Arity • lambdas failed with wrong arguments but proc is ok 2011 8 25
  • 18. methods class MyClass def initialize(value) @x = value end def my_method @x end end object = MyClass.new(1) m = object.method :my_method m.call a lambda is evaluated in the scope Method is evaluated in the scope of its object 2011 8 25
  • 19. Callable object wrap-up Blocks: Evaluated in the scope in which they’re defined. Procs: Objects of class Proc. Like blocks, they are evaluated in the scope where they’re defined. Lambdas: Also objects of class Proc but subtly different from regular proc. Methods: Bound to an object, they are evaluated in that object’s scope. They can also be unbound from their scope and rebound to the scope of another object. 2011 8 25
  • 20. DSL • DSL for individual event • Shared among events • Adding setup instruction • Using & operator to pass setup • Not using global variables 2011 8 25