Defining and calling lambdas or procs (Ruby)

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 = lambda do |arg|
      puts arg
    end
    

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')
    
Judith Roth over 6 years ago
This website uses short-lived cookies to improve usability.
Accept or learn more