Full Stack Founder · a live cohort for developersjoin the waitlist →
← Back to Blog
interviewThibault “Tibo” Denizet

Ruby Blocks : Procs and Lambdas

Sixth article in the Prepare for a Ruby job interview series. In this article, we're going to talk about the Blocks in Ruby : Procs and Lambas.

Proc and Lambda are anonymous function that can be moved around in your code as variable.

pr = Proc.new { |a, b| a + b }
p pr.call(1, 2)

--

l = lambda { |a, b| a + b }
p l.call(1, 2)

The main difference between those is that a return statement in a proc will behave like a part of the calling method (and return from it) :

def test_proc
  Proc.new { return 1 }.call
  return 0
end

--

def test_lambda
  lambda { return 1 }.call
  return 0
end

--

p test_proc # => 1
p test_lambda # => 0

As you can see, the proc returned from the test_proc method.

Passing a block to a method can be done in different ways.

With the & (ampersand) symbol :

def super_method(arg1, &block)
  p arg1
  block.call
end

super_method('Hi!') { p "I'm a proc!" }

--

# => "Hi!"
# => "I'm a proc!"

With yield :

def super_method(arg1)
  p arg1
  yield
end

super_method('Hi!') { p "I'm a proc!" }

--

# => "Hi!"
# => "I'm a proc!"

You can also simply pass the block as an argument :

def super_method(arg1, pr)
  p arg1
  pr.call
end

pr = Proc.new { p "I'm a proc!" }
super_method('Hi!', pr)

--

# => "Hi!"
# => "I'm a proc!"

Checkout the next article about the Splat operator .

$ whoami

Tibo, creator of Devmystify

Tibo

Hi, I'm the creator of Devmystify and author of Modular Rails and Master Ruby Web APIs.

I built a 6-figure consulting business while living in Thailand and now share practical advice on turning dev skills into a business: consulting, digital products, and SaaS.

join the cohort waitlist →

Comments

Loading comments...

> one email a week, real numbers

The other half of the job

You can already build. The free ebook answers the rest: which business is right for you, the real numbers behind each path, and the ladder to climb without quitting your job.

join 2,700+ developers · unsubscribe anytime · no spam, only receipts

Ruby Blocks : Procs and Lambdas | Devmystify