From: "mame (Yusuke Endoh) via ruby-core" Date: 2025-06-11T09:38:09+00:00 Subject: [ruby-core:122513] [Ruby Feature#21435] Kernel#optional as a conditional #then Issue #21435 has been updated by mame (Yusuke Endoh). To be honest, when I see a code fragment like `.optional { it.decorate if it.respond_to? :decorate }`, I couldn't understand the intended behavior at all. Personally, I feel that this actually increases cognitive complexity rather than reducing it. It's not just that the method name `optional` feels inappropriate. I think the existence of a method with such tricky behavior itself adds to cognitive complexity. In terms of cognitive complexity, I find it much easier to understand when the logic is written out explicitly, even if it's more verbose, like this: ```ruby @record = Record.find(record_id) @record = @record.decorate if @record.respond_to?(:decorate) ``` ---------------------------------------- Feature #21435: Kernel#optional as a conditional #then https://bugs.ruby-lang.org/issues/21435#change-113736 * 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/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/