Lambda Functions in Ruby

RubyServer Side ProgrammingProgramming

In Ruby, we can take the help of lambda functions when we want to use anonymous functions. They are also treated like objects in Ruby, as everything in Ruby is treated as objects.

Syntax

The syntax of declaring a lambda function is shown below.

lambda = lambda {}

Or, we can also make use of lambda literal.

lambda = ->() {}

Let's first check the type of the lambda functions in Ruby with the help of a program.

Example 1

Consider the code shown below

some_lambda_function = lambda { puts "Welcome to TutorialsPoint!"}

puts some_lambda_function.class

Output

Proc

Example 2

Now let's create another program where we will use our own lambda function and then explore the different types of approaches that we can use to execute these lambda functions.

some_lambda_function = lambda { puts "Welcome to TutorialsPoint!"}

some_lambda_function.[]
some_lambda_function.call
some_lambda_function.()
some_lambda_function.===

In the above example, we can see that there are four different approaches that we can use to invoke a lambda function in Ruby.

Output

Welcome to TutorialsPoint!
Welcome to TutorialsPoint!
Welcome to TutorialsPoint!
Welcome to TutorialsPoint!

Example 3

We can also pass arguments to the lambda functions in Ruby. Consider the code shown below.

some_lambda_function = lambda { | name | puts "Welcome to TutorialsPoint " + name}

some_lambda_function.call("Mukul")

Output

Welcome to TutorialsPoint Mukul
raja
Updated on 25-Jan-2022 11:52:10

Advertisements