Ruby : Block, Proc and, lambda

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
1 of 24

Recommended

Rust言語紹介 by
Rust言語紹介Rust言語紹介
Rust言語紹介Paweł Rusin
1.7K views33 slides
Go ahead, make my day by
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
877 views35 slides
Lisp как универсальная обертка by
Lisp как универсальная оберткаLisp как универсальная обертка
Lisp как универсальная оберткаVsevolod Dyomkin
1.2K views25 slides
MP in Clojure by
MP in ClojureMP in Clojure
MP in ClojureKent Ohashi
4.1K views53 slides
Free Monads Getting Started by
Free Monads Getting StartedFree Monads Getting Started
Free Monads Getting StartedKent Ohashi
1K views31 slides
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas... by
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...
ECSE 221 - Introduction to Computer Engineering - Tutorial 1 - Muhammad Ehtas...Muhammad Ulhaque
978 views18 slides

More Related Content

What's hot

Beauty and Power of Go by
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of GoFrank Müller
3.3K views46 slides
Rust-lang by
Rust-langRust-lang
Rust-langAnthony Broad-Crawford
3.1K views54 slides
TCO in Python via bytecode manipulation. by
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.lnikolaeva
1.1K views19 slides
Introduction to go by
Introduction to goIntroduction to go
Introduction to goJaehue Jang
2.9K views45 slides
C++の話(本当にあった怖い話) by
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)Yuki Tamura
27.6K views70 slides
TypeScript Introduction by
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionHans Höchtl
674 views36 slides

What's hot(20)

Beauty and Power of Go by Frank Müller
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
Frank Müller3.3K views
TCO in Python via bytecode manipulation. by lnikolaeva
TCO in Python via bytecode manipulation.TCO in Python via bytecode manipulation.
TCO in Python via bytecode manipulation.
lnikolaeva1.1K views
Introduction to go by Jaehue Jang
Introduction to goIntroduction to go
Introduction to go
Jaehue Jang2.9K views
C++の話(本当にあった怖い話) by Yuki Tamura
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)
Yuki Tamura27.6K views
TypeScript Introduction by Hans Höchtl
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
Hans Höchtl674 views
Rust concurrency tutorial 2015 12-02 by nikomatsakis
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
nikomatsakis2.4K views
Rust Mozlando Tutorial by nikomatsakis
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorial
nikomatsakis1.5K views
Python opcodes by alexgolec
Python opcodesPython opcodes
Python opcodes
alexgolec5K views
Python in 90mins by Larry Cai
Python in 90minsPython in 90mins
Python in 90mins
Larry Cai3.7K views
Evgeniy Muralev, Mark Vince, Working with the compiler, not against it by Sergey Platonov
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
Sergey Platonov6K views
The Ring programming language version 1.5.3 book - Part 35 of 184 by Mahmoud Samir Fayed
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 by Oliver N
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
Oliver N847 views
C++totural file by halaisumit
C++totural fileC++totural file
C++totural file
halaisumit215 views
Groovy puzzlers по русски с Joker 2014 by Baruch Sadogursky
Groovy puzzlers по русски с Joker 2014Groovy puzzlers по русски с Joker 2014
Groovy puzzlers по русски с Joker 2014
GoLightly: A Go Library For Building Virtual Machines by Eleanor McHugh
GoLightly: A Go Library For Building Virtual MachinesGoLightly: A Go Library For Building Virtual Machines
GoLightly: A Go Library For Building Virtual Machines
Eleanor McHugh486 views
Implementation of 'go-like' language constructions in scala [english version] by Ruslan Shevchenko
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 Shevchenko694 views

Similar to Ruby : Block, Proc and, lambda

ruby1_6up by
ruby1_6upruby1_6up
ruby1_6uptutorialsruby
226 views5 slides
ruby1_6up by
ruby1_6upruby1_6up
ruby1_6uptutorialsruby
190 views5 slides
Tres Gemas De Ruby by
Tres Gemas De RubyTres Gemas De Ruby
Tres Gemas De RubyLeonardo Soto
416 views29 slides
Pydiomatic by
PydiomaticPydiomatic
Pydiomaticrik0
924 views61 slides
Python idiomatico by
Python idiomaticoPython idiomatico
Python idiomaticoPyCon Italia
908 views61 slides
Fun with Lambdas: C++14 Style (part 2) by
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
51.6K views30 slides

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

Pydiomatic by rik0
PydiomaticPydiomatic
Pydiomatic
rik0924 views
Fun with Lambdas: C++14 Style (part 2) by Sumant Tambe
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 Tambe51.6K views
Ti1220 Lecture 2: Names, Bindings, and Scopes by Eelco Visser
Ti1220 Lecture 2: Names, Bindings, and ScopesTi1220 Lecture 2: Names, Bindings, and Scopes
Ti1220 Lecture 2: Names, Bindings, and Scopes
Eelco Visser4.4K views
Ruby 程式語言入門導覽 by Wen-Tien Chang
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
Wen-Tien Chang1.6K views
GR8Conf 2011: Effective Groovy by GR8Conf
GR8Conf 2011: Effective GroovyGR8Conf 2011: Effective Groovy
GR8Conf 2011: Effective Groovy
GR8Conf1.4K views
Patterns for JVM languages JokerConf by Jaroslaw Palka
Patterns for JVM languages JokerConfPatterns for JVM languages JokerConf
Patterns for JVM languages JokerConf
Jaroslaw Palka1.1K views
Dataflow: Declarative concurrency in Ruby by Larry Diehl
Dataflow: Declarative concurrency in RubyDataflow: Declarative concurrency in Ruby
Dataflow: Declarative concurrency in Ruby
Larry Diehl1.6K views
PyCon KR 2019 sprint - RustPython by example by YunWon Jeong
PyCon KR 2019 sprint  - RustPython by examplePyCon KR 2019 sprint  - RustPython by example
PyCon KR 2019 sprint - RustPython by example
YunWon Jeong190 views
Rapid Development with Ruby/JRuby and Rails by elliando dias
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
elliando dias901 views
Python decorators by Alex Su
Python decoratorsPython decorators
Python decorators
Alex Su2.2K views

Recently uploaded

Voice Logger - Telephony Integration Solution at Aegis by
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at AegisNirmal Sharma
17 views1 slide
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze by
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng TszeDigital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng TszeNUS-ISS
19 views47 slides
RADIUS-Omnichannel Interaction System by
RADIUS-Omnichannel Interaction SystemRADIUS-Omnichannel Interaction System
RADIUS-Omnichannel Interaction SystemRADIUS
15 views21 slides
Spesifikasi Lengkap ASUS Vivobook Go 14 by
Spesifikasi Lengkap ASUS Vivobook Go 14Spesifikasi Lengkap ASUS Vivobook Go 14
Spesifikasi Lengkap ASUS Vivobook Go 14Dot Semarang
35 views1 slide
How the World's Leading Independent Automotive Distributor is Reinventing Its... by
How the World's Leading Independent Automotive Distributor is Reinventing Its...How the World's Leading Independent Automotive Distributor is Reinventing Its...
How the World's Leading Independent Automotive Distributor is Reinventing Its...NUS-ISS
15 views25 slides
ChatGPT and AI for Web Developers by
ChatGPT and AI for Web DevelopersChatGPT and AI for Web Developers
ChatGPT and AI for Web DevelopersMaximiliano Firtman
181 views82 slides

Recently uploaded(20)

Voice Logger - Telephony Integration Solution at Aegis by Nirmal Sharma
Voice Logger - Telephony Integration Solution at AegisVoice Logger - Telephony Integration Solution at Aegis
Voice Logger - Telephony Integration Solution at Aegis
Nirmal Sharma17 views
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze by NUS-ISS
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng TszeDigital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze
Digital Product-Centric Enterprise and Enterprise Architecture - Tan Eng Tsze
NUS-ISS19 views
RADIUS-Omnichannel Interaction System by RADIUS
RADIUS-Omnichannel Interaction SystemRADIUS-Omnichannel Interaction System
RADIUS-Omnichannel Interaction System
RADIUS15 views
Spesifikasi Lengkap ASUS Vivobook Go 14 by Dot Semarang
Spesifikasi Lengkap ASUS Vivobook Go 14Spesifikasi Lengkap ASUS Vivobook Go 14
Spesifikasi Lengkap ASUS Vivobook Go 14
Dot Semarang35 views
How the World's Leading Independent Automotive Distributor is Reinventing Its... by NUS-ISS
How the World's Leading Independent Automotive Distributor is Reinventing Its...How the World's Leading Independent Automotive Distributor is Reinventing Its...
How the World's Leading Independent Automotive Distributor is Reinventing Its...
NUS-ISS15 views
[2023] Putting the R! in R&D.pdf by Eleanor McHugh
[2023] Putting the R! in R&D.pdf[2023] Putting the R! in R&D.pdf
[2023] Putting the R! in R&D.pdf
Eleanor McHugh38 views
Special_edition_innovator_2023.pdf by WillDavies22
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdf
WillDavies2216 views
The Importance of Cybersecurity for Digital Transformation by NUS-ISS
The Importance of Cybersecurity for Digital TransformationThe Importance of Cybersecurity for Digital Transformation
The Importance of Cybersecurity for Digital Transformation
NUS-ISS27 views
.conf Go 2023 - Data analysis as a routine by Splunk
.conf Go 2023 - Data analysis as a routine.conf Go 2023 - Data analysis as a routine
.conf Go 2023 - Data analysis as a routine
Splunk93 views
Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu... by NUS-ISS
Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu...Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu...
Architecting CX Measurement Frameworks and Ensuring CX Metrics are fit for Pu...
NUS-ISS37 views
SAP Automation Using Bar Code and FIORI.pdf by Virendra Rai, PMP
SAP Automation Using Bar Code and FIORI.pdfSAP Automation Using Bar Code and FIORI.pdf
SAP Automation Using Bar Code and FIORI.pdf
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV by Splunk
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV
Splunk88 views
Combining Orchestration and Choreography for a Clean Architecture by ThomasHeinrichs1
Combining Orchestration and Choreography for a Clean ArchitectureCombining Orchestration and Choreography for a Clean Architecture
Combining Orchestration and Choreography for a Clean Architecture
ThomasHeinrichs169 views
Future of Learning - Yap Aye Wee.pdf by NUS-ISS
Future of Learning - Yap Aye Wee.pdfFuture of Learning - Yap Aye Wee.pdf
Future of Learning - Yap Aye Wee.pdf
NUS-ISS41 views

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