Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
A Ruby is a dynamic, open-source programming language focusing on productivity and simplicity. The syntax of Ruby is natural and easy to understand for the users. Ruby is a popular language for many things, from web development to data analysis. Ruby programming language is highly flexible, and developers can change how the language works due to its flexibility. Ruby is an interpreted language.
In this blog, we will discuss hiding setup and cleanup in a block method in ruby with the help of some examples.
Code Blocks and Iterator
Code Block is an object that consists of Ruby code and consists of the context necessary to execute the ruby code. Code blick is a method with no name. Many languages have code blocks in ruby, such as C++'s function objects, C's function pointer, Python's lambdas, and java's anonymous inner class. Ruby cannot be written without code blocks; it is essential to this programming language.
Example:
[1,2,3].each { |i| puts i }
# 1
# 2
# 3
You can also try this code with Online Ruby Compiler
So in this blog, we will see the problem of hiding setup and cleanup in a block method.
Hiding setup and cleanup in a Block Method
We have heard many times that Ruby blocks are referred to as Closures. So let's see the example in which we will see the cleanup and hiding setup in a block method in ruby.
Problem
We have a setup method that every time needs to run before custom code or a cleanup method that needs to run after custom code. And it's hard to remember to call the setup and cleanup method.
Solution
We have to create a method that will run the hiding setup code, bind it to the code block with the custom code, and then run the cleanup code. To make sure that the cleanup code will always run, even if the custom code throws an exception, we will use a begin/finally block:
//defining a function
def between_setup_and_cleanup
setup
begin
yield
finally
cleanup
end
end
You can also try this code with Online Ruby Compiler
Now we will see an example. In this example, we have DOCTYPE and an HTML tag at the starting of an HTML document. And in the end, it closes the HTML tag that was opened earlier. This will reduce some of the work when we are generating HTML files:
def write_html(out, doctype=nil)
doctype ||= %{<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 5.01 Transitional//EN"
"http://www.w3.org/TR/html5/loose.dtd">}
out.puts doctype
out.puts '<html>'
begin
yeild out
ensure
out.puts '</html>'
end
end
write_html($stdout) do |out|
out.puts '<h1>Sorry, the Web is closed.</h1>'
end
You can also try this code with Online Ruby Compiler
In this way, we can perform a hiding setup and cleanup in a Block Method in ruby.
Discussion
This technique shows up most of the time when there are insufficient resources that should be closed when we are done with them. We have seen that programmers are lazy, but ruby makes it easy to be lazy and even do the right thing. The above method accepts a code block that customizes an already open file. First, they open the file, call the code block, and then close the file once we are done.
open('output.txt', 'w') do |out|
out.puts 'Sorry, the filesystem is also closed.'
end
You can also try this code with Online Ruby Compiler
We can create an entire HTML document by nesting blocks inside each other. Let's see the small ruby DGI that results the same document as previous example:
#!/usr/bin/ruby
# closed_cgi.rb
require 'cgi'
c = CGI.new("html4")
c.out do
c.html do
c.h1 { 'Sorry, the Web is closed.' }
end
end
You can also try this code with Online Ruby Compiler
Here, pay attention to the multiple levels of blocks: the block passed to CGI#out is simply calling CGI#html to generate the DOCTYPE and the <html> tags.The <html> tags consists of result of a call to CGI#h1, that encloses some plain text in <h1> tags. The code produces the following output:
Content-Type: text/html
Content-Length: 137
You can also try this code with Online Ruby Compiler
In the same way, the XmlMarkup class in ruby's builder gem works, we can write ruby code that take after the structure if the documents it creates:
gem 'builder'
require 'builder'
xml = Builder::XmlMarkup.new.message('type' => 'apology') do |b|
b.content('Sorry, Web Services are closed.')
end
puts xml
# <message type="apology">
# <content>Sorry, Web Services are closed.</content>
# </message>
You can also try this code with Online Ruby Compiler
A method in Ruby is a set of expressions that returns a value. Within a method, you can set your code into subroutines that can be quickly initiated from other areas of their program.
Are variables objects in Ruby?
A variable in ruby is nothing but a label or tag for a container. A variable can contain almost everything like a string, an array, a hash, etc.
What is Metaprogramming in ruby?
Metaprogramming in ruby is a technique by which you can write code that writes code by itself dynamically at runtime. In simple words, we can define methods and classes during runtime.
What are blocks in Ruby?
The block is simply a chunk of code always enclosed within braces in ruby. A block is always initiated from a function inside the same name as that of a block.
What are the data types in Ruby?
Ruby consists of data types such as Numbers, Strings, Hashes, Boolean, Symbols, Arrays, etc.
Conclusion
In this article, we have discussed the Hiding Setup and Cleanup in a Block Method in ruby with the help of some examples. We started with the introduction of ruby, then we saw Code Blocks and Iterators concept, and then the hiding setup and cleanup in a block Method in ruby with the help of an example.