Defining and calling lambdas or procs (Ruby)

Updated . Posted . Visible to the public. Repeats.

Ruby has the class Proc which encapsulates a "block of code". There are 2 "flavors" of Procs:

  • Those with "block semantics", called blocks or confusingly sometimes also procs
  • Those with "method semantics", called lambdas

lambdas

They behave like Ruby method definitions:

  • They are strict about their arguments.
  • return means "exit the lambda"

How to define a lambda

  1. With the lambda keyword

    test = lambda do |arg|
      puts arg
    end
    
  2. With the lambda literal -> (since Ruby 1.9.1)

    test = ->(arg) do
      puts arg
    end
    

blocks

They behave like do-blocks or simply "segments of code":

  • They try to be smart about their arguments:
    • When the block accepts multiple arguments and receives an array, it will splat the array
    • When the block receives less arguments than required, it will set the missing ones to nil
    • When the block receives too many arguments, it will discard some
  • return means "exit the surrounding method"
    • for only "exiting the block" use break (takes an argument!)
    • there also are next and continue

How to define a block

  1. With the proc keyword:

    test = proc do |arg|
      puts arg
    end
    
  2. With Proc.new:

    test = Proc.new do |arg|
      puts arg
    end
    
  3. By passing a block to a method:

    def capture_block(&block)
      block
    end
    
    test = capture_block do |arg|
      puts arg
    end
    

How to call a block

Calling a block or a lambda works the same way. There are multiple possibilities

  1. call (we prefer this)

    test.call('hello world')
    
  2. Square brackets (could easily be mistaken for a hash)

    test['hello world']
    
  3. .() (weird, isn't it?)

    test.('hello world')
    
Judith Roth
Last edit
Klaus Weidinger
Keywords
block
License
Source code in this card is licensed under the MIT License.
Posted by Judith Roth to makandra dev (2015-11-24 13:40)