Read more

Defining and calling lambdas or procs (Ruby)

Deleted user #4117
November 24, 2015Software engineer

There are different ways to define a lambda or proc in ruby. [*]

  1. with 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
    
  3. with the proc keyword (which defines a lambda that does not test the given number of arguments):

    test = proc do |arg|
      puts arg
    end
    
Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

[*] Technicalities:

And there are different ways to call them:

  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')
    
Posted to makandra dev (2015-11-24 14:40)