Feature #16374
Updated by sawa (Tsuyoshi Sawada) almost 5 years ago
How about adding a new method to `Object` Object class? ```ruby ``` class Object def nullify &block block.call(self) ? nil : self end end irb(main):139:0> 'asdf'.nullify(&:empty?) #=> => "asdf" irb(main):140:0> ''.nullify(&:empty?) #=> => nil ``` It can be used together for chaining several methods with conditions. E.g. with `&.` &. operator and `#then`: #then: ```ruby ``` irb(main):154:0> [1, 2].nullify(&:empty?)&.then(&:join) #=> => "12" irb(main):155:0> [].nullify(&:empty?)&.then(&:join) #=> => nil irb(main):156:0> [].join #=> => "" irb(main):161:0> 'a b'.nullify(&:empty?)&.then(&:split) #=> => ["a", "b"] irb(main):162:0> ''.nullify(&:empty?)&.then(&:split) #=> => nil irb(main):163:0> ''.split #=> => [] ``` P.S. A similar opposite operation is available as a chain of [`then.detect`](https://ruby-doc.org/core-2.6.5/Object.html#method-i-then) ['then.detect'](https://ruby-doc.org/core-2.6.5/Object.html#method-i-then)