Project

General

Profile

Actions

Feature #16374

open

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

Added by cvss (Kirill Vechera) over 4 years ago. Updated over 4 years ago.

Status:
Open
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

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0