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

Lambda

A lambda is a careful kind of Proc that checks how many inputs you gave it, like a strict form that must be completely filled. It is written with the arrow shortcut or the word lambda.

In this page:

  1. Lambda
Syntax
ruby
lambda_name = lambda { |param| expression }
lambda_name = ->(param) { expression }
lambda_name.call(argument)

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)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using lambda and calling with the wrong number of arguments, which raises ArgumentError.
  2. Writing lambda { |x| x * x } and calling it as square(4), which raises NoMethodError; a lambda must be called with square.call(4), square.(4) or square[4].
  3. Forgetting .call and printing the lambda object instead of its result.
🔒

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.