SlideShare una empresa de Scribd logo
1 de 25
Functional techniques in Ruby ,[object Object]
The Big Idea Functions are data too.
list  =  [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] # in a language like Java, C, C++ you could write something like: for (int i  =   0 ; i  <  list.size(); i ++ ){ puts list[i]; } for  i  in  list puts i end list.each {| i | puts i }
{| i | puts i} | i |  # are the parameters of the block puts i  # is the body of the block {}  # define the start and end of the block def   anon_function ( i ) puts i end
Block Proc lambda closure What’s in a name?
# pseudo ruby code class   Array def   each for (i = 0 ; i  <   self .size; i ++ ) yield   self [i] end end end yield   self [i]
yield   1   => {|1| puts  1 } yield   2   => {|2| puts  2 } yield   3   => {|3| puts  3 } yield   4   => {|4| puts  4 } yield   5   => {|5| puts  5 } yield   6   => {|6| puts  6 } yield   7   => {|7| puts  7 } yield   8   => {|8| puts  8 } yield   9   => {|9| puts  9 } yield   10  => {|10| puts  10 } list.each {| i | puts i }
class   Array # still pseudocode def   each ( block ) for (i = 0 ; i  <   self .size; i ++ ) block.call( self [i]) end end end block.call( self [i])
block.call( 1 )  => {|1| puts  1 } block.call( 2 )  => {|2| puts  2 } block.call( 3 )  => {|3| puts  3 } block.call( 4 )  => {|4| puts  4 } block.call( 5 )  => {|5| puts  5 } block.call( 6 )  => {|6| puts  6 } block.call( 7 )  => {|7| puts  7 } block.call( 8 )  => {|8| puts  8 } block.call( 9 )  => {|9| puts  9 } block.call( 10 ) => {|10| puts  10 }
.call has to go somewhere block.class  # => Proc list.each {| i | puts i } == b  =   Proc . new  {| i | puts i } list.each( & b)
b  =  lambda {| i | puts i } list.each( & b) b  =   Proc . new  {| i | puts i } list.each( & b) b  =  proc {| i | puts i } list.each( & b) == ==
Quick Review ,[object Object],[object Object]
Now for the why? ,[object Object]
pattern of computation list.each {| i | puts i } where’s the iteration code?
another example def   even? ( num ) num  %   2   ==   0 end def   reject_evens ( list ) return_list  =   Array . new list.each  do  | item | return_list  <<  item  unless  even?(item) end return_list end def   reject_odds ( list ) return_list  =   Array . new list.each  do  | item | return_list  <<  item  if  even?(item) end return_list end list  =  [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] reject_evens(list) #=> [1,3,5,7,9] reject_odds(list) #=> [2,4,6,8]
def   reject ( list,  & block ) return_list  =   Array . new list.each  do  item return_list  <<  item  if  block.call(item) end return_list end list  =  [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] reject(list) {| i | even?(i) } #=> [1,3,5,7,9] reject(list) {| i | !even?(i) } #=> [2,4,6,8]
def   make_rejector ( & block ) lambda  do  | list | return_list  =   Array . new list.each  do  | item | return_list  <<  element  unless  block.call(item) end return_list end end list  =  [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] odd_rejector  =  make_rejector {| i | odd?(i) } odd_rejector.call(list) #=> [2,4,6,8]
Closure ,[object Object],[object Object]
def   make_rejector ( & block ) lambda  do  | list | return_list  =   Array . new list.each  do  | item | return_list  <<  element  if  block.call(item) end return_list end end
example closures def   complement   f lambda {|* args |  not  f.call( * args) } end even?  =  lambda {| n | n  %   2   ==   0  } odd?  =  complement(even?) odd?.call( 1 )  # true odd?.call( 2 )  # false
def   compose   f, g lambda {|* args | f.call(g.call( * args)) } end find  =  lambda {| name |  User .find_by_username(name) } auth  =  lambda {| u |  User .authenticate(u) } find_and_authenticate  =  compose(auth, find) find_and_authenticate.call( &quot;Erock&quot; )  #=> true
in the wild def   returning ( value )  #active_support yield (value) value end returning([])  do  | list | list  <<   1 list  <<   2 end # => [1,2]
respond_to  do  | format | format.html format.js {  render   :action  =>  &quot;index.rjs&quot; } format.xml {  render   :xml  =>  @user .to_xml } end # Rails RESTful routing map.resources  :users   do  | user | user.resources  :blogs end
# Rspec require   'bowling' describe  Bowling   do before( :each )  do @bowling   =   Bowling . new end it  &quot;should score 0 for gutter game&quot;   do 20 .times {  @bowling .hit( 0 ) } @bowling .score.should  ==   0 end end
more info ,[object Object],[object Object],[object Object],[object Object],[object Object]

Más contenido relacionado

La actualidad más candente

CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - ReferenceMohammed Sikander
 
F# Presentation
F# PresentationF# Presentation
F# Presentationmrkurt
 
Operators
OperatorsOperators
OperatorsKamran
 
Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)IoT Code Lab
 
Python Basic Operators
Python Basic OperatorsPython Basic Operators
Python Basic OperatorsSoba Arjun
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Reuven Lerner
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionEelco Visser
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScripttmont
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)Thai Pangsakulyanont
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 
Advance python programming
Advance python programming Advance python programming
Advance python programming Jagdish Chavan
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1Abdul Haseeb
 
An Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with JavascriptAn Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with JavascriptDoug Sparling
 

La actualidad más candente (20)

CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
 
F# Presentation
F# PresentationF# Presentation
F# Presentation
 
Operators
OperatorsOperators
Operators
 
Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)Chapter 1 Basic Programming (Python Programming Lecture)
Chapter 1 Basic Programming (Python Programming Lecture)
 
Python Basic Operators
Python Basic OperatorsPython Basic Operators
Python Basic Operators
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
C# 7.0, 7.1, 7.2
C# 7.0, 7.1, 7.2C# 7.0, 7.1, 7.2
C# 7.0, 7.1, 7.2
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Advance python programming
Advance python programming Advance python programming
Advance python programming
 
175035 cse lab-05
175035 cse lab-05 175035 cse lab-05
175035 cse lab-05
 
Operators in python
Operators in pythonOperators in python
Operators in python
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
An Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with JavascriptAn Introduction to Functional Programming with Javascript
An Introduction to Functional Programming with Javascript
 
Exp 3 3 d422
Exp 3 3  d422Exp 3 3  d422
Exp 3 3 d422
 

Similar a Functional techniques in Ruby

Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009David Pollak
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovyTed Leung
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfRahul04August
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mark Needham
 
Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Skills Matter
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScriptJosh Mock
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applicationsJoe Jiang
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairMark
 
Evolving with Java - How to Remain Effective
Evolving with Java - How to Remain EffectiveEvolving with Java - How to Remain Effective
Evolving with Java - How to Remain EffectiveNaresha K
 
Useful javascript
Useful javascriptUseful javascript
Useful javascriptLei Kang
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick touraztack
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 

Similar a Functional techniques in Ruby (20)

Groovy
GroovyGroovy
Groovy
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
 
SeaJUG March 2004 - Groovy
SeaJUG March 2004 - GroovySeaJUG March 2004 - Groovy
SeaJUG March 2004 - Groovy
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Steady with ruby
Steady with rubySteady with ruby
Steady with ruby
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#
 
Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScript
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love AffairCoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
 
Antlr V3
Antlr V3Antlr V3
Antlr V3
 
Evolving with Java - How to Remain Effective
Evolving with Java - How to Remain EffectiveEvolving with Java - How to Remain Effective
Evolving with Java - How to Remain Effective
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 

Último

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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 educationjfdjdjcjdnsjd
 
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 WoodJuan lago vázquez
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 

Último (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

Functional techniques in Ruby

  • 1.
  • 2. The Big Idea Functions are data too.
  • 3. list = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] # in a language like Java, C, C++ you could write something like: for (int i = 0 ; i < list.size(); i ++ ){ puts list[i]; } for i in list puts i end list.each {| i | puts i }
  • 4. {| i | puts i} | i | # are the parameters of the block puts i # is the body of the block {} # define the start and end of the block def anon_function ( i ) puts i end
  • 5. Block Proc lambda closure What’s in a name?
  • 6. # pseudo ruby code class Array def each for (i = 0 ; i < self .size; i ++ ) yield self [i] end end end yield self [i]
  • 7. yield 1 => {|1| puts 1 } yield 2 => {|2| puts 2 } yield 3 => {|3| puts 3 } yield 4 => {|4| puts 4 } yield 5 => {|5| puts 5 } yield 6 => {|6| puts 6 } yield 7 => {|7| puts 7 } yield 8 => {|8| puts 8 } yield 9 => {|9| puts 9 } yield 10 => {|10| puts 10 } list.each {| i | puts i }
  • 8. class Array # still pseudocode def each ( block ) for (i = 0 ; i < self .size; i ++ ) block.call( self [i]) end end end block.call( self [i])
  • 9. block.call( 1 ) => {|1| puts 1 } block.call( 2 ) => {|2| puts 2 } block.call( 3 ) => {|3| puts 3 } block.call( 4 ) => {|4| puts 4 } block.call( 5 ) => {|5| puts 5 } block.call( 6 ) => {|6| puts 6 } block.call( 7 ) => {|7| puts 7 } block.call( 8 ) => {|8| puts 8 } block.call( 9 ) => {|9| puts 9 } block.call( 10 ) => {|10| puts 10 }
  • 10. .call has to go somewhere block.class # => Proc list.each {| i | puts i } == b = Proc . new {| i | puts i } list.each( & b)
  • 11. b = lambda {| i | puts i } list.each( & b) b = Proc . new {| i | puts i } list.each( & b) b = proc {| i | puts i } list.each( & b) == ==
  • 12.
  • 13.
  • 14. pattern of computation list.each {| i | puts i } where’s the iteration code?
  • 15. another example def even? ( num ) num % 2 == 0 end def reject_evens ( list ) return_list = Array . new list.each do | item | return_list << item unless even?(item) end return_list end def reject_odds ( list ) return_list = Array . new list.each do | item | return_list << item if even?(item) end return_list end list = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] reject_evens(list) #=> [1,3,5,7,9] reject_odds(list) #=> [2,4,6,8]
  • 16. def reject ( list, & block ) return_list = Array . new list.each do item return_list << item if block.call(item) end return_list end list = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] reject(list) {| i | even?(i) } #=> [1,3,5,7,9] reject(list) {| i | !even?(i) } #=> [2,4,6,8]
  • 17. def make_rejector ( & block ) lambda do | list | return_list = Array . new list.each do | item | return_list << element unless block.call(item) end return_list end end list = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] odd_rejector = make_rejector {| i | odd?(i) } odd_rejector.call(list) #=> [2,4,6,8]
  • 18.
  • 19. def make_rejector ( & block ) lambda do | list | return_list = Array . new list.each do | item | return_list << element if block.call(item) end return_list end end
  • 20. example closures def complement f lambda {|* args | not f.call( * args) } end even? = lambda {| n | n % 2 == 0 } odd? = complement(even?) odd?.call( 1 ) # true odd?.call( 2 ) # false
  • 21. def compose f, g lambda {|* args | f.call(g.call( * args)) } end find = lambda {| name | User .find_by_username(name) } auth = lambda {| u | User .authenticate(u) } find_and_authenticate = compose(auth, find) find_and_authenticate.call( &quot;Erock&quot; ) #=> true
  • 22. in the wild def returning ( value ) #active_support yield (value) value end returning([]) do | list | list << 1 list << 2 end # => [1,2]
  • 23. respond_to do | format | format.html format.js { render :action => &quot;index.rjs&quot; } format.xml { render :xml => @user .to_xml } end # Rails RESTful routing map.resources :users do | user | user.resources :blogs end
  • 24. # Rspec require 'bowling' describe Bowling do before( :each ) do @bowling = Bowling . new end it &quot;should score 0 for gutter game&quot; do 20 .times { @bowling .hit( 0 ) } @bowling .score.should == 0 end end
  • 25.