Holla Tech - Learn

Lambdas
 

Lambdas are a variation of Procs. A lambda is actually an instance of the Proc class.
To create a lambda in Ruby, you use the following syntax: 

talk = lambda {puts “Hi”

 

Alternatively, the following syntax can be used:

talk = ->() {puts “Hi”

 

Just like with procs, you use the call method to execute the lambda: 

talk.call 

 

NOTE!
In other programming languages, a lambda is commonly referred to as an anonymous function.

Lambdas
 

Lambdas as very similar to procs. However, there are some important differences.
The first difference between procs and lambdas is how arguments are handled.
Lambdas check the number of arguments, while procs do not.
For example:

talk = lambda { |x| puts “Hello #{x}” }
talk_proc = Proc.new { |x| puts “Hello #{x}” }

talk.call “David”
# outputs “Hello David”

talk_proc.call “Amy”
# outputs “Hello Amy” 

  

As you can see, the lambda and proc worked the same way, when the number of arguments is correct.
However, if we try to call them with incorrect number of arguments:

talk_proc.call
# ouputs Hello

talk.call
# outputs “Error: wrong number of arguments (given 0, expected 1)” 

 

As you can see, when a lambda expects an argument, you need to pass those arguments or an Error will occur. However, in the case of the Proc, if the argument is not passed it automatically defaults to nil.

NOTE!
A second difference between a lambda and a Proc is how the return statement is handled. When a lambda encounters a return statement it returns execution to the enclosing method. However, when a Proc encounters a return statement it jumps out of itself, as well as the enclosing method.

BACK NEXT

CLICK ON THE BUTTON BELOW TO GO TO THE RUBY MAIN COURSE PAGE. 

RUBY MAIN COURSE PAGE

 


© License: All Rights Reserved 


CONTACT HOLLA TECH – LEARN SUPPORT