" Start your business on internet, we are here to help you "

We are Software Development and Technical Service providing company from kathmandu Nepal. We use latest technologies to fulfill your requirements

What is Lambda in Programming?

Ruby     Published at about 2 months ago    Bishnu Basyal

What is Lambda in Programming?

What is Lambda in Programming?

Lambda comes from the Lambda Calculus and refers to anonymous functions in programming.
A lambda is a type of function, defined inline. Along with a lambda you also usually have some kind of variable type that can hold a reference to a function.

Here we are going to explain basic of lambda using Ruby programming.

Lambdas in Ruby are also objects.

 

How to create Lambda in Ruby?

It is very simple we can create lambda in Ruby using the arrow syntax (->) or lambda keyword.

 

Creating lambda using arrow syntax( -> )

my_lambda = -> { "Hello World" }
my_lambda[]

output: 

"Hello World"

 

Creating lambda using lambda keyword

my_lambda = lambda { "Hello World" }
my_lambda[]

output: 

"Hello World"

 

Lambda using the arrow syntax accepting argument

my_lambda = ->(name) {"Hello #{name}"}
my_lambda['John']   

output: 

"Hello John"

 

Lambda accepting multiple arguments

my_lambda = lambda do |one, two, three|
  puts "I am #{one}"
  puts "I am #{two}"
  puts "I am #{three}"
end

my_lambda[1, 2, 3] #lambda call

output:

I am 1
I am 2
I am 3

 

You can also use .() to call lambda

my_lambda = lambda do |one, two, three|
  puts "I am #{one}"
  puts "I am #{two}"
  puts "I am #{three}"
end

my_lambda.(1, 2, 3) #lambda call

output:

I am 1
I am 2
I am 3

 

Find square of a number using lambda

def square(n)  
  my_square = lambda { |number| number * number }
  my_square[n]
end

square(3)

output:

 9

 

Lambda is not useful in terms of defining very basic functionality, but it is useful if you want to have methods/functions that are not instantly called or reduced.

 

Thank you.....

 

To Top