Menu
Coddy logo textTech

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)   # 14

A 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 icon

Challenge

Easy

Create 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:

  1. The result of calling tripler.call(10)
  2. The input numbers tripled (use map(&tripler)) and joined with ,

For input 1,2,3, the output is:

30
3, 6, 9

Cheat sheet

Proc – reusable block stored in a variable:

double = proc { |n| n * 2 }
double.call(5)   # 10

Lambda – 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 ", "
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow