DEV Community

loading...

ensure doesn't return value implicitly

okuramasafumi profile image OKURA Masafumi ・1 min read

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

Discussion (0)

pic
Editor guide