Blocks for Transactions

Blocks or chunks of code that can be used for transactional control which in our example would have it open a file, process it then make sure that same file is closed after processing before exiting the code. There is an automatic function that ensures this and we will discuss it further in the following example which is a form of simple (meaning it does not take into consideration any errors whatsoever) code below.

class File
def File.takeAndDosomething(*args)
f=File.open(*args)
yield f
f.close()
end
end

File.takeAndDosomething(“testfile”, “r”) do |aFile|
print while aFile.gets
end

This sample code would give you the following output:
This is line one
This is line two
This is line three
And so on……………

The results will be discussed in the next post where we dissect what we have just done.

This entry was posted in Development, Programming Basics, Programming Language and tagged , . Bookmark the permalink. Comments are closed, but you can leave a trackback: Trackback URL.