Open In App

Lambda Function – Ruby

Improve
Improve
Like Article
Like
Save
Share
Report

In Computer Programming, Lambda functions are anonymous functions. Lambda functions in Ruby are no different. Since everything in Ruby is treated as an object, lambdas are also objects in Ruby. Lambdas in Ruby allow us to wrap data and logic in a portable package. 
 

Syntax to create Lambda function in Ruby:

lambda = lambda {}  

Alternatively, we can also use literal lambda.  

lambda = ->() {}  

Lambda function is an instance of the Proc class of Ruby. 

# Creating a lambda function
my_lambda_function = lambda { puts " GeeksforGeeks " }

# Getting class of lambda
my_lambda_function.class

On Execution : 

Proc

Working with Lambdas in Ruby 

Let’s define a lambda function 

my_lambda_function = lambda { puts "Hello, Geeks !" }

We have different ways to call this function. We can use my_lambda.call, my_lambda.() , my_lambda.[] or my_lambda.=== to call the lambda function . 
Example : 

Ruby




# Creating a lambda function
my_lambda_function = lambda { puts "Hello, Geeks" }
 
 
# Different ways to call a lambda function
my_lambda_function.call
 
my_lambda_function.()
 
my_lambda_function.[]
 
my_lambda_function.===


Output:

Hello, Geeks
Hello, Geeks
Hello, Geeks
Hello, Geeks

To pass arguments in the lambda function, we can either use normal lambda syntax or use the literal lambda operator ” -> ” 
Example 1: 

# Creating lambda function with arguments 
# Using lambda keyword

lambda_with_args = lambda {| s | puts "Hello "+ s }

# Calling lambda function by passing arguments
lambda_with_args.call("Geeks")

Output: 

Hello Geeks

Example 2: 

Ruby




# Creating lambda function with arguments
# Using literal lambda function
 
lambda_with_args = -> (s) { puts "Hello "+ s }
 
# Calling lambda function by passing arguments
lambda_with_args.call("Geeks")


Output:

Hello Geeks

To use lambda functions along with a normal function, we can pass lambda function as an argument. 
Example: 

Ruby




# Lambda function to add 10
add_10 = lambda { |num| num + 10 }
 
# Lambda function to multiply with 2
multiply_2 = lambda { |num| num * 2 }
 
# A Function using lambda
def using_lambda_with_functions(lambda, number)
 
  puts lambda.call(number)
 
end
 
 
# Passing lambda to function
using_lambda_with_functions(add_10, 10)
 
using_lambda_with_functions(multiply_2, 20)


Output: 

20
40


Last Updated : 16 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads