How to Use the call() Method in Ruby
-
Creating a
Proc
Class in Ruby -
Use the
proc
Keyword in Ruby -
Use the
lambda
Keyword in Ruby -
Use the
lambda
Literal Syntax in Ruby
Ruby’s call
method is used on Procs. To understand Proc
, we need first to understand Block
.
Ruby blocks
are anonymous functions that are enclosed in a do-end
statement or curly braces {}
.
The Proc
block can be stored in a variable, passed to a method or another Proc
, and invoked independently using the call
method.
Below are different ways of creating a Proc
.
Creating a Proc
Class in Ruby
square_proc = proc { |x| x**2 }
puts square_proc.call(4)
Output:
16
In the above example, we argued the call
method because the square_proc
defined a parameter x
.
If we did not define any parameter in the Proc, we wouldn’t need to pass any argument to call
at the point of invoking the proc.
This is not a very good case, though. Below is another example with no parameter defined.
empty_proc = proc { 4 * 4 }
puts square_proc.call
Output:
16
Use the proc
Keyword in Ruby
multiplication_proc = proc { |x, y| x * y }
puts multiplication_proc.call(4, 5)
Output:
20
The above methods show how to create regular Procs
. There’s another flavor of Proc called lambda
.
Procs
and Lambdas
are usually used interchangeably, though with a few differences. The methods below show how to create this flavor of procs called lambda
.
Use the lambda
Keyword in Ruby
square_lambda = ->(x) { x**2 }
puts square_lambda.call(5)
Output:
35
Use the lambda
Literal Syntax in Ruby
multiplication_lambda = ->(x, y) { x * y }
puts multiplication_lambda.call(5, 6)
Output:
30