What the Heck are Code Blocks, Procs, Lambdas, and Closures in Ruby?

  1. Definitions of Code Block, Proc, Lambda, and Closure
  2. Constructions
  3. Calling a Code Block/Proc/Lambda
  4. Passing and Returning Procs

1. Definitions

  • A code block is a block of code. Some people also call a code block a block.
  • A proc is an object that contains a code block. It provides a way to save up a code block and execute it later.
  • A lambda is special kind of proc (more on that later).
  • A closure is a function that: 1. can be passed around as a variable and 2. binds to the same scope in which it was created (more on that later). To different extents, code blocks, procs, and lambdas can be seen as closures. Closure is a higher-level concept compared to Code Block, Proc, and Lambda.

2. Constructions

  • Code Block: {} OR do end
  • Proc: Proc.new OR proc followed by a code block
  • Lambda: lambda OR -> (stabby lambda) followed by a code block
  • Closure: again, Code blocks, procs, and lambdas can be seen as different forms of closures.

3. Calling a code block/proc/lambda

  • You call it.
  • You yield it.[1]

4. Passing and Returning Procs

--

--

--

Engineering @Gusto; Making Videos at https://www.youtube.com/channel/UCN3_BBsNo7ePr9bjPMeXcSg; Writing at sihui.io

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sihui Huang

Sihui Huang

Engineering @Gusto; Making Videos at https://www.youtube.com/channel/UCN3_BBsNo7ePr9bjPMeXcSg; Writing at sihui.io

More from Medium

Common Behavioral Patterns (part 2/3)

Function Composition: how is it worth and how easy is it to implement

Inheritance

SOLID: The Open-Closed Principle and the Double-Edged Sword