Project

General

Profile

Feature #16374

Object#nullify to provide scalars with the effect similar to Enumerable#reject

Added by cvss (Kirill Vechera) 11 months ago. Updated 11 months ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:<unknown>]

Description

How about adding a new method to Object class?

class Object
    def nullify &block
        block.call(self) ? nil : self
    end
end

'asdf'.nullify(&:empty?) #=> "asdf"
''.nullify(&:empty?) #=> nil

It can be used together for chaining several methods with conditions. E.g. with &. operator and #then:

[1, 2].nullify(&:empty?)&.then(&:join) #=> "12"
[].nullify(&:empty?)&.then(&:join) #=> nil
[].join #=> ""
'a b'.nullify(&:empty?)&.then(&:split) #=> ["a", "b"]
''.nullify(&:empty?)&.then(&:split) #=> nil
''.split #=> []

P.S. A similar opposite operation is available as a chain of then.detect

Also available in: Atom PDF