From: "matz (Yukihiro Matsumoto) via ruby-core" Date: 2025-07-10T08:56:41+00:00 Subject: [ruby-core:122714] [Ruby Feature#21435] Kernel#then_try as a conditional #then Issue #21435 has been updated by matz (Yukihiro Matsumoto). Status changed from Open to Rejected From my point of view, it doesn't make the code clearer. Besides that, the core Ruby does not provide even `#try`. Maybe ActiveSupport wants to add this method, but not in the core. Matz. ---------------------------------------- Feature #21435: Kernel#then_try as a conditional #then https://bugs.ruby-lang.org/issues/21435#change-113991 * Author: Alexander.Senko (Alexander Senko) * Status: Rejected ---------------------------------------- ## What 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) .then_try { it.decorate if it.respond_to? :decorate } ``` Or, even shorter for Rails users: ```ruby @record = Record.find(record_id) .then_try { it.try :decorate } ``` ## Why The intent is to **make it visible at a glance that a statement _may_ affect the result**, but not necessarily does so. Without the proposed method, one needs to read and parse the whole block to know that. It should help to read longer processing chains, for those who prefer chains and `#then` to plain old iterative approach. ## Naming It is discussible. I have just two ideas yet: - `then_try` - `optional` - `maybe` ## Reference implementation ```ruby # Yields self to the block and returns the result of the block if it���s # truthy, and self otherwise. def then_try tap do result = yield(self) or next break result end end ``` -- 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/