SlideShare a Scribd company logo
1 of 24
Download to read offline
Block, Proc and, lambda




                          2
Matthieu Segret
Formateur Ruby on Rails @human_coders




                                        1
Block




        3
Block

names = ["Matz","DHH","Aaron"]

names.each do |name|
  puts name
end


names.each { |name| puts name }
                                  4
yield


def call_this_block_twice
  yield
  yield
end

                                        Matz
call_this_block_twice { puts "Matz" }   Matz




                                               5
yield - Arguments


def call_this_block
  yield("Matz")
end


call_this_block {|name| puts name}   Matz




                                            6
yield - Return value


def puts_this_block
  block_result = yield
  puts block_result
end

puts_this_block {"Matz"}   Matz




                                    7
yield - Optional block


def call_this_block
  yield("Matz")
end


call_this_block                 no block given




                                                 8
yield - Optional block


def call_this_block
  yield("Matz") if block_given?
end


call_this_block




                                     9
yield - Scope 1


def call_this_block
  yield
end

x = 5
puts "value of x before: #{x}"   value of x before: 5
call_this_block { x += 1 }
puts "value of x after: #{x}"    value of x after: 6




                                                        10
yield - Scope 2

def call_this_block
  x = 100
  yield
  puts "value of x at end of call_this_block_x: #{x}"
end

x = 5                                   value of x at end of
call_this_block { x += 1 }             call_this_block_x: 100


puts "value of x after: #{x}"           value of x after: 6



                                                                11
What if we wanted to store this
 block, for execution later?


      {|name| puts name}




                                  12
Proc & lambda




                13
Proc & lambda
                                                         Proc
my_proc = Proc.new {|x| puts x}
my_proc.call("Matz")                   Matz


                                                     Lambda
my_lambda = lambda {|x| puts x}
my_lambda.call("DHH")                   DHH


                                              Lambda Ruby 1.9
my_lambda = ->(x) {puts x}
my_lambda.call("Aaron")                Aaron



                                                                14
Proc vs lambda : return
                                                                       Lambda
def bar
  f = lambda { return "return from inside lambda" }
  f.call
  return "return from bar"
end
puts bar                                                 return from bar


                                                                           Proc
def foo
  f = Proc.new { return "return from inside proc" }
  f.call
  return "return from foo"
end
puts foo                                              return from inside proc


                                                                                  15
Proc vs lambda : arity

                                                             Lambda
my_lambda = lambda {|x,y| puts "(#{x},#{y})"}
my_lambda.call(1,2,3)                           wrong number of
my_lambda.call(1)                                arguments ...




                                                                  Proc
my_proc = Proc.new {|x,y| puts "(#{x},#{y})"}
my_proc.call(1,2,3)                                  (1,2)
my_proc.call(1)                                       (1,)




                                                                         16
Multiple lambda


def post(success, error)
  ...
  if ...
    success.call
  else
    error.call
  end
end

post(-> {puts "Sent!"}, -> {raise 'Auth Error'})




                                                   17
Lambda to block

names = ["Matz","DHH","Aaron"]
names.each do |name|
  puts name
end



names = ["Matz","DHH","Aaron"]
printer = lambda {|name| puts name}
names.each( & printer)                lambda to block




                                                        18
Proc to block

names = ["Matz","DHH","Aaron"]
names.each do |name|
  puts name
end



names = ["Matz","DHH","Aaron"]
printer = Proc.new {|name| puts name}
names.each( & printer)                  Proc to block




                                                        19
Block to Proc

def call_this_block
  yield("Matz")
end



def call_this_block(&block)           block to Proc
  block.call("Matz")
end




                                                      20
Symbol#to_proc


tweets.map { |tweet| tweet.user }




tweets.map(&:user)                  Symbol to Proc




                                                     21
Method#to_proc

def method_user(tweet)
  tweet.user
end


method(:method_user)



tweets.map(&method(:method_user))   Method to Proc




                                                     22
23
Thanks
@matthieusegret




                  24

More Related Content

What's hot

Rust-lang
Rust-langRust-lang
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
C++totural file
C++totural fileC++totural file
C++totural file
halaisumit
 

What's hot (20)

Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
Rust-lang
Rust-langRust-lang
Rust-lang
 
TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorial
 
Python opcodes
Python opcodesPython opcodes
Python opcodes
 
Python in 90mins
Python in 90minsPython in 90mins
Python in 90mins
 
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against itEvgeniy Muralev, Mark Vince, Working with the compiler, not against it
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it
 
The Ring programming language version 1.5.3 book - Part 35 of 184
The Ring programming language version 1.5.3 book - Part 35 of 184The Ring programming language version 1.5.3 book - Part 35 of 184
The Ring programming language version 1.5.3 book - Part 35 of 184
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
 
C++totural file
C++totural fileC++totural file
C++totural file
 
Briefly Rust
Briefly RustBriefly Rust
Briefly Rust
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
 
C++ tutorial
C++ tutorialC++ tutorial
C++ tutorial
 
GoLightly: A Go Library For Building Virtual Machines
GoLightly: A Go Library For Building Virtual MachinesGoLightly: A Go Library For Building Virtual Machines
GoLightly: A Go Library For Building Virtual Machines
 
Implementation of 'go-like' language constructions in scala [english version]
Implementation of 'go-like' language constructions in scala [english version] Implementation of 'go-like' language constructions in scala [english version]
Implementation of 'go-like' language constructions in scala [english version]
 

Similar to Ruby : Block, Proc and, lambda

Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
Eelco Visser
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
Wen-Tien Chang
 
GR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective Groovy
GR8Conf
 
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
elliando dias
 
Python decorators
Python decoratorsPython decorators
Python decorators
Alex Su
 

Similar to Ruby : Block, Proc and, lambda (20)

ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
 
ruby1_6up
ruby1_6upruby1_6up
ruby1_6up
 
Tres Gemas De Ruby
Tres Gemas De RubyTres Gemas De Ruby
Tres Gemas De Ruby
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
 
Kotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsKotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functions
 
Ti1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
Mini-curso JavaFX Aula2
Mini-curso JavaFX Aula2Mini-curso JavaFX Aula2
Mini-curso JavaFX Aula2
 
GR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective Groovy
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Patterns for JVM languages JokerConf
Patterns for JVM languages JokerConfPatterns for JVM languages JokerConf
Patterns for JVM languages JokerConf
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in Ruby
 
Matlab functions
Matlab functionsMatlab functions
Matlab functions
 
PyCon KR 2019 sprint - RustPython by example
PyCon KR 2019 sprint  - RustPython by examplePyCon KR 2019 sprint  - RustPython by example
PyCon KR 2019 sprint - RustPython by example
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
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
 
Python decorators
Python decoratorsPython decorators
Python decorators
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
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
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
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...
 
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...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 

Ruby : Block, Proc and, lambda

  • 1. Block, Proc and, lambda 2
  • 2. Matthieu Segret Formateur Ruby on Rails @human_coders 1
  • 3. Block 3
  • 4. Block names = ["Matz","DHH","Aaron"] names.each do |name| puts name end names.each { |name| puts name } 4
  • 5. yield def call_this_block_twice yield yield end Matz call_this_block_twice { puts "Matz" } Matz 5
  • 6. yield - Arguments def call_this_block yield("Matz") end call_this_block {|name| puts name} Matz 6
  • 7. yield - Return value def puts_this_block block_result = yield puts block_result end puts_this_block {"Matz"} Matz 7
  • 8. yield - Optional block def call_this_block yield("Matz") end call_this_block no block given 8
  • 9. yield - Optional block def call_this_block yield("Matz") if block_given? end call_this_block 9
  • 10. yield - Scope 1 def call_this_block yield end x = 5 puts "value of x before: #{x}" value of x before: 5 call_this_block { x += 1 } puts "value of x after: #{x}" value of x after: 6 10
  • 11. yield - Scope 2 def call_this_block x = 100 yield puts "value of x at end of call_this_block_x: #{x}" end x = 5 value of x at end of call_this_block { x += 1 } call_this_block_x: 100 puts "value of x after: #{x}" value of x after: 6 11
  • 12. What if we wanted to store this block, for execution later? {|name| puts name} 12
  • 14. Proc & lambda Proc my_proc = Proc.new {|x| puts x} my_proc.call("Matz") Matz Lambda my_lambda = lambda {|x| puts x} my_lambda.call("DHH") DHH Lambda Ruby 1.9 my_lambda = ->(x) {puts x} my_lambda.call("Aaron") Aaron 14
  • 15. Proc vs lambda : return Lambda def bar f = lambda { return "return from inside lambda" } f.call return "return from bar" end puts bar return from bar Proc def foo f = Proc.new { return "return from inside proc" } f.call return "return from foo" end puts foo return from inside proc 15
  • 16. Proc vs lambda : arity Lambda my_lambda = lambda {|x,y| puts "(#{x},#{y})"} my_lambda.call(1,2,3) wrong number of my_lambda.call(1) arguments ... Proc my_proc = Proc.new {|x,y| puts "(#{x},#{y})"} my_proc.call(1,2,3) (1,2) my_proc.call(1) (1,) 16
  • 17. Multiple lambda def post(success, error) ... if ... success.call else error.call end end post(-> {puts "Sent!"}, -> {raise 'Auth Error'}) 17
  • 18. Lambda to block names = ["Matz","DHH","Aaron"] names.each do |name| puts name end names = ["Matz","DHH","Aaron"] printer = lambda {|name| puts name} names.each( & printer) lambda to block 18
  • 19. Proc to block names = ["Matz","DHH","Aaron"] names.each do |name| puts name end names = ["Matz","DHH","Aaron"] printer = Proc.new {|name| puts name} names.each( & printer) Proc to block 19
  • 20. Block to Proc def call_this_block yield("Matz") end def call_this_block(&block) block to Proc block.call("Matz") end 20
  • 21. Symbol#to_proc tweets.map { |tweet| tweet.user } tweets.map(&:user) Symbol to Proc 21
  • 22. Method#to_proc def method_user(tweet) tweet.user end method(:method_user) tweets.map(&method(:method_user)) Method to Proc 22
  • 23. 23