tags:

views:

174

answers:

3

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'.

+3  A: 

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.

Ken Bloom
A: 

Seems like you have to explicitly return true, ensure might just not return the last value automagically.

Yoann Le Touche
+1  A: 

See this blog post for an overview of how ensure behaves with both implicit and explicit returns.

mikej
that's a good blog post. But the author did not explicitly mentioned that unless return is mentioned return values are discarded.
Roger
Found it on RubyFlow 30 seconds ago. That's a very good post.
Yoann Le Touche