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
?
Wikipedia describes blocks as anonymous functions.
Block is not a function, it is a complementary method syntax.
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
language construct for using closures
constructors:
Proc.new {}
proc {} - preferred by Ruby style guide
pass arguments through 'pipes'
proc { |arg1, arg2| p arg1, arg2 }
will "answer" when called with:
#call() - OK
#[] - NOT OK
#.() - HORRIBLE
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.
Handles | arguments | return keyword |
---|---|---|
proc | loosely | passes control to the outer scope |
lambda | strictly | passes control to a current scope |
Lambdas behave like methods.
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..
STEP foo { puts "Within a block!" }
STEP proc { puts "Within a block!" }
STEP def foo(&block) block.call end
In the wild, Ruby can even become "JQuerish".
Doing some caching.
You are probably using it already.
Methods can become object as well: m = bar.method(:foo) # m is a method #foo m.call # callable object