DEV Community

loading...

ensure doesn't return value implicitly

OKURA Masafumi
Ruby/Rails developer from Japan. The chief organizer of Kaigi on Rails ( https://kaigionrails.org ). Vimmer. He/Him
・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)