Home » Ruby programming

Lambdas in Ruby

Ruby Lambdas: In this tutorial, we are going to learn about the Lambdas in Ruby programming language with examples.
Submitted by Hrithik Chandra Prasad, on November 14, 2019

Ruby Lambdas

In the last tutorial, we have seen what are procs, how they are implemented in Ruby and their examples? Lambdas are pretty similar to Procs. They are also used to store a set of instructions or a method inside a variable which is also the feature of Procs. You can call lambdas anywhere in your code wherever required.

Let us see the basic syntax of Lambdas in Ruby for understanding them in a better way,

    variable_name = lambda {|argument1,argument2| argument1 * argument2}

You can observe that the syntax is quite similar to Procs but in Proc, we need to use ".new" method to create a Proc but here writing lambda is enough for declaring a lambda. In the above syntax, we are using curly braces and inside them, we are passing the arguments inside || block or pair of alteration symbol. We have demonstrated by multiplying the argument whereas you can do any type of processing inside the block.

Now, let us go through an example of Lambda, so that we will be able to see its implementation in Ruby code.

var = lambda {|arg1,arg2,arg3| puts arg1*arg2+arg3}
var[12,45,33]

Output

573

In the above code, we are creating lambda which is used to process some kind of arithmetic calculations. We are calling it by writing its name and passing arguments inside square braces like [].

You can also create a lambda in the following way. It is known as stabby lambda. The example is given below,

var = -> (arg1,arg2,arg3) {puts arg1*arg2+arg3}
var[12,45,33]

Output

573

We have created a stabby lambda here. The above code is modified to create a better understanding of differences that come in terms of syntax. Here we are passing arguments inside () braces and the processing is done inside the curly braces { }.

Calling a lambda

We have seen this in Procs as well. Lambdas are called in the same way as Procs. There are two ways, first one is just by writing the name of the variable along with the arguments inside the square braces and the second one is by the help of the call method. The syntax is given below,

    variable_name.call( argument1, argument2)

Let us see its practical implementation with the help of example given below,

var = lambda{
	|num|
	i = 1 
	while(i<=10)
		p num * i
		i = i + 1
	end
}
var.call(34)

Output

34
68
102
136
170
204
238
272
306
340

In the above code, we are using lambda.call() method for calling the lambda.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.