SlideShare a Scribd company logo
Functional techniques in Ruby @erockenjew
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 Functions are “First Class” objects Higher Order Procedures accept functions as arguments
Now for the why? Because First Class functions allow us to abstract and combine patterns of computation
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 A Proc that binds locally scoped variables by ‘closing’ over them Captures local variables and keeps them around even after they’ve gone out of scope
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 SICP:   http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-001Spring-2005/CourseHome / http://en.wikipedia.org/wiki/Closure_(computer_science ) http://www.slideshare.net/jashmenn/higher-order-procedures-in-ruby-15799/ http://www.artima.com/intv/closures.html http://www.randomhacks.net/articles/2007/02/01/some-useful-closures-in-ruby

More Related Content

PPTX
Input processing and output in Python
PPTX
Functional Programming in Javascript - IL Tech Talks week
PDF
Thinking in Functions: Functional Programming in Python
PDF
Functional programming in Python
PDF
Functional Programming with JavaScript
PPTX
Functional programming in JavaScript
PDF
Chapter 2 Decision Making (Python Programming Lecture)
PDF
Operator overloading
Input processing and output in Python
Functional Programming in Javascript - IL Tech Talks week
Thinking in Functions: Functional Programming in Python
Functional programming in Python
Functional Programming with JavaScript
Functional programming in JavaScript
Chapter 2 Decision Making (Python Programming Lecture)
Operator overloading

What's hot (20)

PPT
CPP Language Basics - Reference
PPTX
F# Presentation
PPT
Operators
PDF
Chapter 1 Basic Programming (Python Programming Lecture)
PDF
Python Basic Operators
PDF
Functional Python Webinar from October 22nd, 2014
PDF
CS4200 2019 | Lecture 2 | syntax-definition
PPT
Introduction to Functional Programming in JavaScript
PDF
Introduction to Recursion (Python)
PPT
An Overview Of Python With Functional Programming
PPTX
C# 7.0, 7.1, 7.2
PPTX
Functional Programming in JavaScript by Luis Atencio
PPTX
GE8151 Problem Solving and Python Programming
PPTX
Advance python programming
PDF
175035 cse lab-05
PDF
Operators in python
PPTX
Python programming workshop session 1
PPTX
An Introduction to Functional Programming with Javascript
DOCX
Exp 3 3 d422
CPP Language Basics - Reference
F# Presentation
Operators
Chapter 1 Basic Programming (Python Programming Lecture)
Python Basic Operators
Functional Python Webinar from October 22nd, 2014
CS4200 2019 | Lecture 2 | syntax-definition
Introduction to Functional Programming in JavaScript
Introduction to Recursion (Python)
An Overview Of Python With Functional Programming
C# 7.0, 7.1, 7.2
Functional Programming in JavaScript by Luis Atencio
GE8151 Problem Solving and Python Programming
Advance python programming
175035 cse lab-05
Operators in python
Python programming workshop session 1
An Introduction to Functional Programming with Javascript
Exp 3 3 d422
Ad

Similar to Functional techniques in Ruby (20)

PDF
verilog HDL introduction - beginners guide
PPTX
Groovy
ODP
Beginning Scala Svcc 2009
PDF
SeaJUG March 2004 - Groovy
ODP
Scala introduction
PDF
JavaScript Array Interview Questions PDF By ScholarHat
PDF
C++ Searching & Sorting5. Sort the following list using the select.pdf
PPTX
Javascript Basics
ODP
Scala 2 + 2 > 4
PDF
Steady with ruby
PPT
Groovy Introduction - JAX Germany - 2008
PPT
Mixing functional and object oriented approaches to programming in C#
PPT
Mixing Functional and Object Oriented Approaches to Programming in C#
PDF
Story for a Ruby on Rails Single Engineer
PDF
Refactoring to Macros with Clojure
PDF
Composition in JavaScript
ODP
perl usage at database applications
KEY
CoffeeScript - A Rubyist's Love Affair
PPT
Antlr V3
PDF
Evolving with Java - How to Remain Effective
verilog HDL introduction - beginners guide
Groovy
Beginning Scala Svcc 2009
SeaJUG March 2004 - Groovy
Scala introduction
JavaScript Array Interview Questions PDF By ScholarHat
C++ Searching & Sorting5. Sort the following list using the select.pdf
Javascript Basics
Scala 2 + 2 > 4
Steady with ruby
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#
Story for a Ruby on Rails Single Engineer
Refactoring to Macros with Clojure
Composition in JavaScript
perl usage at database applications
CoffeeScript - A Rubyist's Love Affair
Antlr V3
Evolving with Java - How to Remain Effective
Ad

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Empathic Computing: Creating Shared Understanding
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
KodekX | Application Modernization Development
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Cloud computing and distributed systems.
Encapsulation theory and applications.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Empathic Computing: Creating Shared Understanding
MYSQL Presentation for SQL database connectivity
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Chapter 3 Spatial Domain Image Processing.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
KodekX | Application Modernization Development
Review of recent advances in non-invasive hemoglobin estimation
sap open course for s4hana steps from ECC to s4
Network Security Unit 5.pdf for BCA BBA.
The Rise and Fall of 3GPP – Time for a Sabbatical?
Programs and apps: productivity, graphics, security and other tools
Mobile App Security Testing_ A Comprehensive Guide.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Spectral efficient network and resource selection model in 5G networks
Cloud computing and distributed systems.

Functional techniques in Ruby

  • 1. Functional techniques in Ruby @erockenjew
  • 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. Quick Review Functions are “First Class” objects Higher Order Procedures accept functions as arguments
  • 13. Now for the why? Because First Class functions allow us to abstract and combine patterns of computation
  • 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. Closure A Proc that binds locally scoped variables by ‘closing’ over them Captures local variables and keeps them around even after they’ve gone out of scope
  • 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. more info SICP: http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-001Spring-2005/CourseHome / http://en.wikipedia.org/wiki/Closure_(computer_science ) http://www.slideshare.net/jashmenn/higher-order-procedures-in-ruby-15799/ http://www.artima.com/intv/closures.html http://www.randomhacks.net/articles/2007/02/01/some-useful-closures-in-ruby