Issue #13923 has been updated by KonaBlend (Kona Blend).


> ```ruby
> # Class of storage and buffer should include a module (like Closeable)
> # or be checked with respond_to?(:close)
> 
> begin(storage = getStorage(); buffer = storage.get(buffer_id)
>   # ...
> rescue StorageError => e
>   # ...
> end
> # (buffer.close if buffer) rescue nil
> # (storage.close if storage) rescue nil
> ```

maybe new keyword `defer` which simply builds an array of blocks to be called at end of scope;
specifically immediately before the `end` of `ensure` section;
i.e. if there is `ensure` code then `defer` underlying support should come afterwards.

```ruby
begin
  ## underlying support:
  # __deferred = []

  r0 = Expensive.make_resource # might return nil or become nil
  defer { r0.close if r0 } 
  ## underlying support:
  # __deferred << block

  ## sugar
  r1 = Expensive.make_resource 
  defer(r1)
  ## equivalent:
  # defer { r1.close if r1 }

  ## sugar
  defer r2 = Expensive.make_resource
  ## equivalent:
  # defer { r2.close if r2 }
ensure
  ## underlying support:
  # __deferred.each { |block| block.call }
end
```

----------------------------------------
Feature #13923: Idiom to release resources safely, with less indentations
https://bugs.ruby-lang.org/issues/13923#change-66797

* Author: tagomoris (Satoshi TAGOMORI)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
In programs which grabs and releases resources very often, we need to write so much begin-ensure clauses.

```ruby
begin
  storage = getStorage()
  begin
    buffer = storage.get(buffer_id)

    # ...
  ensure
    buffer.close if buffer
  end
rescue StorageError => e
  # ...
ensure
  storage.close if storage
end
```

Such code makes our code fat, and difficult to understand.
I want to write such code like below:

```ruby
# Class of storage and buffer should include a module (like Closeable)
# or be checked with respond_to?(:close)

begin(storage = getStorage(); buffer = storage.get(buffer_id)
  # ...
rescue StorageError => e
  # ...
end
# (buffer.close if buffer) rescue nil
# (storage.close if storage) rescue nil
```

Other languages also have similar features:

* Java: try-with-resources
* Python: with




-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>