
Issue #21435 has been updated by Alexander.Senko (Alexander Senko). matheusrich (Matheus Richard) wrote in #note-3:
I'm sorry, I don't understand the use case, nor how it DRY things up.
The given example shaves off 1 character. What is optional doing? What is "optional" referring to?
The idea is a) to **reduce cognitive complexity** by removing one trivial branch of `if`/`else` statement or an ugly ternary operator, and b) to **highlight explicitly that the statement is conditional** and may leave the result intact in some cases. The method may improve readability of longer processing chains when some of the operations are applied conditionally. Without it, we have to repeat that same `else` branch for every conditional processing in a chain -- that looks a bit cumbersome and not very DRY for me. I'm not a native speaker, sorry. IMO, `optional` indicates that execution is not guaranteed and depends on a condition. Maybe it could be called `maybe` instead. ---------------------------------------- Feature #21435: Kernel#optional as a conditional #then https://bugs.ruby-lang.org/issues/21435#change-113734 * 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/