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:
-
Proc.new {}
-
proc {} - preferred by Ruby style guide
-
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)
-
STEP foo { puts "Within a block!" }
-
STEP proc { puts "Within a block!" }
-
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
Ruby objects with a telephone
By Dario Daic
Ruby objects with a telephone
In this presentation we will take a look at how Ruby implements closures using a Proc class. We are also going to make distinctions between blocks and procs, and procs and lambdas as well.
- 574