An Introduction to Procs, Lambdas and Closures in Ruby

Peter Cooper · 45K views · 2011 · 27:13

Open on YouTube

Python, Ruby & scripting languagesFunctional programmingtutorial

Why Stack Overflow recommends it

Stack Overflow users link it when answering questions about saving blocks as objects, or about how procs and lambdas differ, as a quick overview of the subtle differences.

Recommended by 2 people across 2 different months, 2013 to 2017.

What it is

Peter Cooper gives a 27-minute introduction to procs, lambdas and closures in Ruby, covering what they are and how they differ. It is a screencast-style talk from 2011 aimed at people getting up to speed with the basics.

What people said

Recommends Aaron K · 2013-05 · Stack Overflow · on “Saving a block as an object to a variable without defining a function in ruby”

You can use a proc or lambda. There are some subtle differences between them; and between Ruby versions. A good overview can been seen here: [this video] given by Peter Cooper

Recommends MrPizzaFace · 2014-01 · Stack Overflow · on “Procs and Lambdas for what when we have methods”

Everything in ruby is considered an object. Proc and lambda are fundamentally similar constructs. This topic is highly opinionated as far as usage goes. The key advantages is that they can be easily passed around into other blocks and the syntax is short and sweet. Consider the following very simple examples: multiply = Proc.new {|x,y| x*y} subtract = lambda {|x,y| x-y} add = ->(x,y) {x+y} def do_math (opr, *b) opr.each do |bloc| puts bloc.call(b[0],b[1]) end end do_math([multiply, subtract, add], 10, 5) # => 50 # => 5 # => 15 puts multiply.call(5,5) # => 25 puts subtract.call(5,5) # => 0 puts add.call(5,5) # => 10 To get a better grasp of what they are, watch this video: An Introduction to

Cites Sagar Pandya · 2017-12 · Stack Overflow · on “How to achieve something like mutually binding variables in Ruby?”

You could use Proc [LINK] objects. a = 1 b = a + 7 #=> 8 proc = Proc.new { b = a + 7 } #=> #<Proc:0x0000000001038760@(irb):3> a = 2 proc.call b #=> 9 Quick overview on procs and lambas here [this video] .