Ensuring a return

This one tripped me up for a few minutes today so I thought I’d write something up on it.

Given this code, what do you think it would return:

def foo
  "Hello, world."
ensure
  "Goodbye, cruel world."
end

puts foo

Would it be greeting me or say goodbye? It would go with “Hello”. This is because the ensure block doesn’t normally return anything. It is just used after the method returns to wrap up anything that definitely needs to happen.

How would I force it to return something in ensure? You would need to use ‘return’ explicitly like so:

def foo
  "Hello, world."
ensure
  return "Goodbye, cruel world."
end

Now the method will say goodbye like you expect.

Comments are closed.