Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How ensure works in ruby

Tags:

ruby

checkout this code and the output

def lab   yield   ensure     puts 'in ensure block'     true end  puts lab { puts 'inside inline block'; false }  output is #inside inline block #in ensure block #false 

I was expecting that after the block is executed then ensure will be executed and since ensure returns true , the final output of calling the method would be 'true'.

like image 820
Roger Avatar asked Nov 18 '09 14:11

Roger


People also ask

What does Ruby ensure do?

ensure goes after the last rescue clause and contains a chunk of code that will always be executed as the block terminates. It doesn't matter if the block exits normally, if it raises and rescues an exception, or if it is terminated by an uncaught exception, the ensure block will get run.

What is begin rescue in Ruby?

Similar to PHP's try-catch, Ruby's exception handling begins with the begin-rescue block. In a nutshell, the begin-rescue is a code block that can be used to deal with raised exceptions without interrupting program execution.

How do you catch errors in Ruby?

In Ruby, catch and throw blocks are the lightweight mechanism for error handling and used to jump from the exception when there is no additional work is available in the program. The catch block is used to jump out from the nested block and the block is labeled with a name.

Can we use rescue without begin?

The method definition itself does the work of begin , so you can omit it. You can also do this with blocks. Now, there is one more way to use the rescue keyword without begin .


1 Answers

The ensure block's return value is discarded -- it's just a way to clean up after the function does whatever it's supposed to (and returns the appropriate value). The reason for this is because it allows you to put several return statements (or raise statements) in different places in the function body, without having to duplicate the cleanup code in different places in the function.

like image 157
Ken Bloom Avatar answered Sep 25 '22 20:09

Ken Bloom