ensure doesn't return value implicitly

okuramasafumi

OKURA Masafumi

Posted on February 27, 2021

ensure doesn't return value implicitly

In Ruby, ensure clause ensures that the code block is executed when an exception is raised or not.

def foo
  'foo'
ensure
  puts 'ensure'
end

foo # => 'ensure' is output
Enter fullscreen mode Exit fullscreen mode

However, the value in ensure clause is not returned implicitly.

def foo
  'foo'
ensure
  'ensure'
end

foo # => 'foo', not 'ensure'
Enter fullscreen mode Exit fullscreen mode

You need to return value explicitly with return.

def foo
  'foo'
ensure
  return 'ensure'
end

foo # => 'ensure'
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
okuramasafumi
OKURA Masafumi

Posted on February 27, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related