Ruby objects with a telephone

What is a callable object?
What is an anonymous function?
Anonymous function is the one that is not bound to an identifier.
Object is callable if it responds to the #call method.

block

proc

Proc

lambda

->

?

?

?

?

?

{    }

do/end

?

BLOCKS (1/3)

BLOCKS (2/3)

Wikipedia describes blocks as anonymous functions.
Block is not a function, it is a complementary method syntax.

BLOCKs (3/3)

To execute a block from within a method, you use yield keyword.

It is not possible to #call a block!
Syntax:
  • {}     - one-liners
  • do/end - multi-liners

PROCs (1/3)

Proc class

procs (2/3)

  • language construct for using closures
  • constructors:

procs (3/3)

  • pass arguments through 'pipes'
    • proc { |arg1, arg2| p arg1, arg2 }
  • will "answer" when called with:
    • #call() - OK
    • #[]     - NOT OK
    • #.()    - HORRIBLE

lambdas

  • special, much stricter, instance of a Proc class
  • constructors and parameters:
    • lambda { |arg1, arg2| }
    • ->(arg1, arg2) {}
  • #call() it
  • Proc#lambda?
#funfact -'proc' and 'lambda' are not keywords but Kernel methods.

The difference(s)

Handles arguments return keyword
proc loosely passes control to the outer scope
lambda strictly passes control to a current scope
Lambdas behave like methods.

usage of '&' (1/2)

  • inside a method definition:
    • denotes that identifier it binds is not an argument, but a proc object
    • def foo(a, b, &block)
  • on a callers side:
    • array.map(&:map)
    • invokes #to_proc on a object passed
Still confused?! It's OK..

usage of '&' (2/2)

  1. STEP foo { puts "Within a block!" }
  2. STEP proc { puts "Within a block!" }
  3. STEP def foo(&block)
           block.call
         end

rails usage examples (1/3)

In the wild, Ruby can even become "JQuerish".

RAILS usage examples (2/3)

Doing some caching.

RAILS usage examples (3/3)

You are probably using it already.

methods as objects

Methods can become object as well:

m = bar.method(:foo) # m is a method #foo
m.call               # callable object

resources

Made with Slides.com