Ruby has the class Proc
which encapsulates a "block of code". There are 2 "flavors" of Procs
:
- Those with "block semantics", called
blocks
or confusingly sometimes alsoprocs
- Those with "method semantics", called
lambdas
lambdas
They behave like Ruby method definitions:
- They are strict about their arguments.
-
return
means "exit thelambda
"
How to define a lambda
-
With the
lambda
keywordtest = lambda do |arg| puts arg end
-
With the lambda literal
->
(since Ruby 1.9.1)test = ->(arg) do puts arg end
blocks
They behave like do
-blocks or simply "segments of code":
- They try to be smart about their arguments:
- When the block accepts multiple arguments and receives an array, it will splat the array
- When the block receives less arguments than required, it will set the missing ones to
nil
- When the block receives too many arguments, it will discard some
-
return
means "exit the surrounding method"- for only "exiting the
block
" usebreak
(takes an argument!) - there also are
next
andcontinue
- for only "exiting the
How to define a block
-
With the
proc
keyword:test = proc do |arg| puts arg end
-
With
Proc.new
:test = Proc.new do |arg| puts arg end
-
By passing a block to a method:
def capture_block(&block) block end test = capture_block do |arg| puts arg end
How to call a block
Calling a block
or a lambda
works the same way. There are multiple possibilities
-
call
(we prefer this)test.call('hello world')
-
Square brackets (could easily be mistaken for a hash)
test['hello world']
-
.()
(weird, isn't it?)test.('hello world')
Posted by Judith Roth to makandra dev (2015-11-24 13:40)