What is Ruby for "ensure"? Give an Example

Asked

Viewed 497 times

-1

What is "ensure" for in Ruby? Give a Practical Example in which situations it is useful.

I’m studying this site here: tutorialspoint.com/ruby/ruby_exceptions.htm But it’s not very clear about 'ensure' in exceptions. It would be like Python’s Finally?

  • This seems to be an exercise statement. If so, how do you think the answer is? How would you describe the function of ensure?

  • I’m studying this site here: https://www.tutorialspoint.com/ruby/ruby_exceptions.htm But it’s not clear about 'ensure' in exceptions.

1 answer

2


The ensure of Ruby is equivalent to finally of other languages: it defines a block of code that will always be executed, either after the begin, is 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 on Repl.it

The exit would be:

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

If there wasn’t the raise inside the block in begin, the block in rescue would not be executed, only the ensure:

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 the output:

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

It is a useful tool when you need to guarantee (hence the name ensure, ensure in English) that a particular piece of code is executed whether there is a fault or not. A hypothetical example would be, for example, in managing 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

Thus, failing or not the persistence of the data in the database, the connection would be properly closed.

Other readings:

  • Already suspected. Thank you for clarifying enough my doubt.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.