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

Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of GoFrank Müller
 
TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.lnikolaeva
 
Introduction to go
Introduction to goIntroduction to go
Introduction to goJaehue Jang
 
C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)Yuki Tamura
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionHans Höchtl
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02nikomatsakis
 
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/c2goMoriyoshi Koizumi
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorialnikomatsakis
 
Python opcodes
Python opcodesPython opcodes
Python opcodesalexgolec
 
Python in 90mins
Python in 90minsPython in 90mins
Python in 90minsLarry Cai
 
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 itSergey Platonov
 
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 184Mahmoud Samir Fayed
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in GolangOliver N
 
C++totural file
C++totural fileC++totural file
C++totural filehalaisumit
 
Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014Baruch Sadogursky
 
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 MachinesEleanor McHugh
 
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] Ruslan Shevchenko
 

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

Pydiomatic
PydiomaticPydiomatic
Pydiomaticrik0
 
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)Sumant Tambe
 
Kotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsKotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsFranco Lombardo
 
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 ScopesEelco Visser
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Wen-Tien Chang
 
GR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective GroovyGR8Conf
 
Patterns for JVM languages JokerConf
Patterns for JVM languages JokerConfPatterns for JVM languages JokerConf
Patterns for JVM languages JokerConfJaroslaw Palka
 
Dataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in RubyLarry Diehl
 
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 exampleYunWon Jeong
 
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
 
Python decorators
Python decoratorsPython decorators
Python decoratorsAlex 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

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 

Recently uploaded (20)

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 

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