#Objective
###What are Blocks, Procs and Lambda?
- Explain the differences between them
- Ability to perform an action on each element of array using at least two methods
###Quick Review on Loops and Arrays
- Loops
- Arrays
students = ['harry ng', 'max cantor', 'david han', 'adam bray']
students.capitalize # nope!
students.each do |student|
p student.capitalize
end
students.each { |student| p student.capitalize }
###Blocks
- Extremely common in Ruby
###Procs and Lambda
- Come up quite a bit as we're trying to
- shorten,
- modularize, and
- DRY up our code
- DRY - Don't Repeat Yourself
#Let's try
###Procs
- Short name for Procedure
p = Proc.new { |x| puts x * 2 }
[1,2,3].each(&p)
proc = Proc.new { puts "Hello World" }
proc.call
###Lambda
- Lambda Calculus and Anoymous Function
lam = lambda { puts "Hello World" }
lam.call
- Commonly used in Javascript as well
sqsum(x,y) = x*x + y*y #<-- normal function
(x,y) -> x*x + y*y #<-- anonymous function
##Differences between Procs and Lambdas
proc = Proc.new { puts "Hello World" }
lam = lambda { puts "Hello World" }
proc.class
lam.class
proc #<Proc:0x007fcb34b6c450@(pry):1>
lam #<Proc:0x007fcb341bbfc8@(pry):7 (lambda)>
###Lambdas check the number of arguments, while procs do not
lam = lambda { |x| puts x } # creates a lambda that takes 1 argument
lam.call(2) # prints out 2
lam.call # ArgumentError: wrong number of arguments (0 for 1)
lam.call(1,2,3) # ArgumentError: wrong number of arguments (3 for 1)
- In contrast, proc don't care
proc = Proc.new { |x| puts x } # creates a proc that takes 1 argument
proc.call(2) # prints out 2
proc.call # returns nil
proc.call(1,2,3) # prints out 1 and forgets about the extra arguments
###Lambdas and procs treat the ‘return’ keyword differently
def lambda_test
lam = lambda { return }
lam.call
puts "Hello world"
end
# calling lambda_test prints 'Hello World'
lambda_test
def proc_test
proc = Proc.new { return }
proc.call
puts "Hello world"
end
# calling proc_test prints nothing
proc_test
##Quiz
- Create a Proc to capitalize both first and last name of student
- Use a block to loop through an array of students' name
students = ['harry ng', 'max cantor', 'david han', 'adam bray']
# Result
Harry Ng
Max Cantor
David Han
Adam Bray
name_proc = Proc.new { |x| puts x.split(" ").map(&:capitalize).join(" ") }
students.each()&name_proc)
##Things to note
- Recognize how Blocks, Procs, Lambda look like?
- Procs and Lambda is similar, with 2 differences
- Reference to the class note and example if you cannot remember