100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Ruby Blocks & Procs Cheat Sheet

Ruby Blocks & Procs Cheat Sheet

Explains Ruby blocks, Procs, and lambdas, including yield, block_given?, the & operator, and their key behavioral differences.

1 PageIntermediateMar 28, 2026

Blocks Basics

Passing and yielding to implicit blocks.

ruby
# A block is passed implicitly to a method[1, 2, 3].each do |n|  puts n * 2end# Single-line block with braces[1, 2, 3].map { |n| n * 2 }   # => [2, 4, 6]# Defining a method that yields to a blockdef repeat(times)  times.times { |i| yield i }endrepeat(3) { |i| puts "Iteration #{i}" }

Procs & Lambdas

Creating reusable callable objects from blocks.

ruby
# Procsquare = Proc.new { |x| x * x }square.call(4)     # => 16square.(4)         # => 16 (shorthand)square[4]          # => 16# Lambdacube = lambda { |x| x ** 3 }cube = ->(x) { x ** 3 }   # stabby lambda syntaxcube.call(3)              # => 27# Converting a block to a Proc with &def run_it(&block)  block.call(10)endrun_it { |x| puts x }

Blocks vs Procs vs Lambdas

Key behavioral differences to remember.

  • return behavior- return inside a lambda exits just the lambda; return inside a Proc exits the enclosing method
  • Arity checking- Lambdas raise ArgumentError on the wrong number of arguments; Procs silently ignore extras or fill missing ones with nil
  • lambda?- Proc#lambda? returns true for lambdas and false for plain Procs, letting you inspect which one you have
  • yield- Calls the block implicitly passed to the current method without naming it as a parameter
  • block_given?- Returns true if the current method call included a block, used to branch behavior
  • & operator- Prefixing a parameter with & converts a block to an explicit Proc, or converts a Proc/Symbol into a block when calling

Symbol#to_proc Shorthand

Compact block syntax using the & operator with symbols.

ruby
# Symbol#to_proc shorthandnames = ["alice", "bob", "carol"]names.map(&:upcase)          # => ["ALICE", "BOB", "CAROL"]names.select(&:empty?)       # equivalent to { |n| n.empty? }# Passing an existing proc/lambda as a blockis_even = ->(n) { n.even? }(1..10).select(&is_even)     # => [2, 4, 6, 8, 10]
Pro Tip

Use lambda (or ->) instead of Proc.new when you need strict argument checking and a return that only exits the lambda itself — this avoids surprising early returns from the enclosing method.

Was this cheat sheet helpful?

Explore Topics

#RubyBlocksProcs#RubyBlocksProcsCheatSheet#Programming#Intermediate#BlocksBasics#ProcsLambdas#BlocksVsProcsVsLambdas#SymbolToProcShorthand#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech

Professional Web Designing Services

  • Responsive Websites
  • E-commerce Solutions
  • SEO Friendly Design
  • Fast & Secure
  • Support & Maintenance
Get a Free Quote

Related Glossary Terms

Share this Cheat Sheet