Blocks, Procs & Lambdas

Blocks

A block is pretty straightforward.
There’s the do … end block:

If I’ve got an array of numbers:

numbers = [1,2,3,4]
numbers.map do |num|
  num * num
end

or the single-line curly braces block

numbers.each { |num| num * num }

Proc (procedure)

This is kind of a “named” block that you can save and use later. So if you wanted to use and save this block

{ |num| num * num }

somewhere, you’d do:

squared_number = Proc.new { |num| num * num }
squared_number.call
#.call will execute the code within the Proc.

Now say you needed to have the squared number of an array.

array = [2,3,5,6]
array.map { |num| num = squared_proc.call(num) }

All that happened was that the map method will iterate through the array and call the proc (which in this case, is a square of its number), and pass it the numbers that it’s iterating through (num) as an argument.

When to use them:

  • You want to reuse a block of code multiple times.
  • Your method will have one or more callbacks.

Lambdas

Lambdas are a bit like Procs, but with two differences :

1.It checks for arguments it receives and returns an Argument Error if they don’t match. Procs just sets variables to nil. So if we’ve got a new lambda:

squared_number = -> { |num| num * num }
# or
squared_number = lambda { |num| num * num }
squared_number.call # - this will return an argument error, since it needs an argument inside its block.

2. It provides diminutive returns – it doesn’t just stop when it encounters a return statement, like a Proc does, but it returns its value to the method.

def proc_example
  Proc.new { return “Hi there, I’m a new proc!”}.call
  return “This will never be returned.”
end

def lambda_example
  lambda { return “Hi there, I’m a new lambda!”}.call
  return “lambda method is finished here and I will print out”
end

Procs are sort of snippets of code and lambdas are sort of anonymous functions.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>