Procs and Lambdas
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 19 of 56.
A block isn't an object, you can't store it in a variable. When you want a piece of code you can pass around, save, and call later, you wrap it in a Proc or a lambda.
A Proc is created with Proc.new or the proc keyword. Call it with .call:
double = proc { |n| n * 2 }
puts double.call(5) # 10
puts double.call(7) # 14A lambda is similar but stricter, it checks that you pass the right number of arguments. The arrow form -> is the common spelling:
square = ->(n) { n * n }
puts square.call(4) # 16
puts square.(4) # 16 (shorthand for .call)Both can be passed to a method that expects a block by prefixing with &:
[1, 2, 3].map(&double) # [2, 4, 6]
[1, 2, 3].map(&square) # [1, 4, 9]Use a lambda when you want stricter argument checking; use a Proc when you want lighter, more forgiving behavior.
Challenge
EasyCreate a lambda named tripler that takes one number and returns it multiplied by 3.
Then read a comma-separated list of integers and print, on separate lines:
- The result of calling
tripler.call(10) - The input numbers tripled (use
map(&tripler)) and joined with,
For input 1,2,3, the output is:
30
3, 6, 9Cheat sheet
Proc – reusable block stored in a variable:
double = proc { |n| n * 2 }
double.call(5) # 10Lambda – stricter argument checking, arrow syntax:
square = ->(n) { n * n }
square.call(4) # 16
square.(4) # 16 (shorthand)Pass a Proc/lambda to a method expecting a block using &:
[1, 2, 3].map(&double) # [2, 4, 6]Try it yourself
# TODO: define `tripler` as a lambda
numbers = gets.chomp.split(",").map(&:to_i)
# TODO: line 1, print tripler.call(10)
# TODO: line 2, map numbers with &tripler, join with ", "
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier