Ruby has the class Proc which encapsulates a "block of code". There are 2 "flavors" of Procs:
- Those with "block semantics", called
blocksor confusingly sometimes alsoprocs - Those with "method semantics", called
lambdas
lambdas
They behave like Ruby method definitions:
- They are strict about their arguments.
-
returnmeans "exit thelambda"
How to define a lambda
-
With the
lambdakeywordtest = 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
-
returnmeans "exit the surrounding method"- for only "exiting the
block" usebreak(takes an argument!) - there also are
nextandcontinue
- for only "exiting the
How to define a block
-
With the
prockeyword: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)