What is "ensure" in Ruby? Give an Example

-1

What is "ensure" in Ruby? Give a practical example in what situations it is useful.

I'm studying this site here: tutorialspoint.com/ruby/ruby_exceptions.htm But it's not clear about 'ensure' exceptions. Would it be like the finally of Python?

    
asked by anonymous 04.07.2018 / 00:38

1 answer

2

Ruby% is equal to ensure of other languages: it defines a block of code that will always be executed, either after the block in finally , or after catching an exception.

begin
    puts 'Bloco de código que será tentado executar'
    raise 'Algo errado não está certo'
rescue Exception
    puts 'É, algo saiu errado'
ensure
    puts 'Esse trecho sempre será executado'
end

See working at Repl.it

The output would be:

Bloco de código que será tentado executar
É, algo saiu errado
Esse trecho sempre será executado

If there was no begin inside the block in raise , the block in begin would not be executed, only rescue :

begin
    puts 'Bloco de código que será tentado executar'
rescue Exception
    puts 'É, algo saiu errado'
ensure
    puts 'Esse trecho sempre será executado'
end

Producing output:

Bloco de código que será tentado executar
Esse trecho sempre será executado

It is a useful tool when you need to ensure (hence the name ensure , ensure in English) that a particular snippet of code is executed with some failure or not. A hypothetical example would be, for example, in the management of communication with the database and transactions:

begin
    db = Database.new
    db.connect
    db.transaction.start
    db.persist(entity)
    db.transaction.commit
rescue Exception
    db.transaction.rollback
ensure
    db.close
end

So, failing or not persisting the data in the database, the connection would be properly closed.

Further readings:

04.07.2018 / 01:19