
Issue #21435 has been updated by nobu (Nobuyoshi Nakada). I agree that the pattern sometimes appears. But the name `optional` feels kind of ambiguous or too generic, to me. Alexander.Senko (Alexander Senko) wrote:
Reference implementation:
```ruby # Yields self to the block and returns the result of the block if it’s # truthy, and self otherwise. def optional yield(self) or self end ```
Regarding `respond_to?`, IIRC, isn't ActiveSupport's `try` based on it? ---------------------------------------- Feature #21435: Kernel#optional as a conditional #then https://bugs.ruby-lang.org/issues/21435#change-113730 * Author: Alexander.Senko (Alexander Senko) * Status: Open ---------------------------------------- When chaining, I need sometimes to apply some changes conditionally, like this: ```ruby @record = Record.find(record_id) .then { it.respond_to?(:decorate) ? it.decorate : it } ``` It would be great to DRY it a bit: ```ruby @record = Record.find(record_id) .optional { it.decorate if it.respond_to? :decorate } ``` Reference implementation: ```ruby # Yields self to the block and returns the result of the block if it’s # truthy, and self otherwise. def optional tap do result = yield(self) or next break result end end ``` The name is discussible. -- https://bugs.ruby-lang.org/