How to Use the Ruby call Method

09/26/2021

Contents

In this article, you will learn how to use the Ruby call method.

Using the call method

The call method is a powerful tool in Ruby that allows you to execute a Proc or a lambda. It is a way of invoking a block of code that has been stored in a variable, without having to define a new method. Here’s how you can use the call method in your Ruby code:

Using call with a Proc

my_proc = Proc.new { |x| puts x * 2 }
my_proc.call(10) # Output: 20

In the above code, we create a Proc object and assign it to the variable my_proc. We then pass the argument 10 to the call method, which executes the block of code stored in the Proc object. The output is 20, which is the result of the multiplication operation.

Using call with a lambda

my_lambda = lambda { |x| puts x * 2 }
my_lambda.call(10) # Output: 20

Similar to the above example, we create a lambda object and assign it to the variable my_lambda. We then pass the argument 10 to the call method, which executes the block of code stored in the lambda object.

Passing multiple arguments

my_proc = Proc.new { |x, y| puts x * y }
my_proc.call(10, 20) # Output: 200

In this example, we create a Proc object that takes two arguments x and y. We then pass the arguments 10 and 20 to the call method, which executes the block of code stored in the Proc object.

Returning a value from a Proc or lambda

my_proc = Proc.new { |x| x * 2 }
result = my_proc.call(10)
puts result # Output: 20

Here, we create a Proc object that multiplies its argument by 2 and returns the result. We pass the argument 10 to the call method, which executes the block of code and returns the result. We then store the result in the variable result and output it to the console.

Using call with a block

def my_method(&block)
  block.call
end

my_method { puts "Hello, world!" } # Output: Hello, world!

In this example, we define a method my_method that takes a block as an argument. We then call the call method on the block within the method. Finally, we invoke the my_method method and pass it a block that outputs “Hello, world!” to the console.