← Back to Ruby Course | Chapter 8: Blocks, Procs & Lambdas | Lesson 4 of 6

Lambda

In this page:

  1. Lambda

Lambda

A lambda (created with lambda { ... } or the -> "stabby lambda" syntax) is similar to a Proc but behaves more like a regular method: it enforces the exact number of arguments, and return inside it only exits the lambda itself, not the enclosing method. Lambdas are generally preferred over Procs when you want method-like strictness and behavior. Both Proc and Lambda are instances of the same Proc class under the hood.

Note: The ->(x) { x * x } stabby lambda syntax is the more modern, concise way to write a lambda compared to lambda { |x| x * x }.

Example: Lambda

markup
square = lambda { |x| x * x }
cube = ->(x) { x * x * x }

puts square.call(4)
puts cube.call(3)
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.