Table of contents
1.
Introduction
2.
How to Write a Method that Accepts a Block?
2.1.
Providing Arguments to Yield Statement
3.
Frequently Asked Questions
3.1.
What are Objects in Ruby?
3.2.
What are Methods in Ruby?
3.3.
What is a block in Ruby?
3.4.
What are the main types of blocks in Ruby?
3.5.
What do we need to write a method that accepts a block?
4.
Conclusion
Last Updated: Mar 27, 2024

Writing a Method that Accepts a Block in Ruby

Author Rajat Agrawal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ruby is a general-purpose, dynamic, reflective, object-oriented programming language. Everything in Ruby is an object. Ruby's development aimed to create a user interface between human programmers and the underlying computational machinery.

As there are closures in different programming languages, Ruby have blocks. A block in Ruby is similar to a method but does not belong to an object.

Let’s learn how to write a method that accepts a block in Ruby.

How to Write a Method that Accepts a Block?

You need to do nothing specific to enable your method to accept a block. If the caller passes one in, any method can use it. You may call the block with the yield keyword at any point in your method.

Let’s understand the above statement with examples.

Example 1:

# Ruby program to show a method accepting block using yield statement

# method
def ninjas

	# method statement to be executed
	puts "Ninjas are Coders!"

	# using yield statement
	yield

	# method statement to be executed
	puts "Ninjas are Developers!"

	# using yield statement
	yield
	
end

# block
ninjas{puts "Ninjas are Data Scientists!"}
You can also try this code with Online Ruby Compiler
Run Code

Output:

In the above program, the method name is ninjas. Method statements are initially invoked, demonstrating that Ninjas are Coders!. However, as soon as yield statements are executed, control is transferred to the block, which then executes its own statements, demonstrating that Ninjas are Data Scientists!. When the Block completes, it returns control to the method, which then continues to run from where the yield statement was invoked. 

Example 2:

# Ruby program to show a method accepting block using yield statement

# method
def func(n)
    
    # if block is provided
	if block_given?
    	n.times { yield }

	# if block is not provided
	else
		raise ArgumentError.new("Error! Block is not provided.")
 
	end
end

# block
func(5) { puts "Coding Ninjas!" }

# block is not provided
func(5)
You can also try this code with Online Ruby Compiler
Run Code

Output:

In the above program, the method name is func. We are invoking the method two times, one with the block argument and another without argument. When we provide the argument, it gives the output as Coding Ninjas! Five times. And when the argument is not provided, it will go in the else statement and shows the Error message Error! Block is not provided.

Providing Arguments to Yield Statement

You can provide arguments to yield (which will be given to the block) and act upon the yield statement's value (this is the value of the last statement in the block).

Here is an example of a method that uses the value of the code block and accepts parameters for its block:-

# Ruby program to show a method that uses the value of the code block and accepts parameters for its block.

# method
def ninjas
    
	var1 = yield("Coders")
	puts "Ninjas are best #{var1}!"

	var2 = yield("Developers")
	puts "Ninjas are best #{var2}!"
    
end

# block
ninjas do |designation|
    puts "Ninjas are #{designation}!"
    designation == "Coders" ? "Coders in the World" : "Developers in the World"
end
You can also try this code with Online Ruby Compiler
Run Code

Output:

In the above program, we can see that we are passing an argument to the yield statement and that arguments we can again use as a variable to execute the method statement.

Frequently Asked Questions

What are Objects in Ruby?

In Ruby, everything is an object. All objects have a unique identification; they can also maintain a state and exhibit behavior in response to messages. Usually, these messages are sent out via method calls. A string is an example of a Ruby object.

What are Methods in Ruby?

A Ruby method is a set of statements that returns a result. With the help of methods, one may organize their code into simple-to-use subroutines that can be called from different parts of their program.

What is a block in Ruby?

In Ruby, a block is similar to a method. Ruby blocks enable us to execute any calculations and manipulation in the same manner as we would inside of any method. Therefore, we can say that while blocks in Ruby are identical to any method, they do not belong to any objects.

What are the main types of blocks in Ruby?

There are mainly three types of blocks in Ruby:-

1.) do and end statement blocks.

2.) Inline blocks or with Curly braces.

3.) Block with arguments.

What do we need to write a method that accepts a block?

You need to do nothing specific to enable your method to accept a block. If the caller passes one in, any method can use it. You may call the block with the yield keyword at any point in your method.

Conclusion

In this article, we have extensively discussed how to write a method that accepts a Block in Ruby with the help of code examples. 

If you want to learn more, check out our articles on Object Marshalling in RubyTainting Objects in RubyCopying Objects In RubyHow To Invoke Global Functions In Ruby?, and Object References in Ruby.

Do upvote our blog to help other ninjas grow.

Happy Coding!

Live masterclass