Actions
Feature #16374
openObject#nullify to provide scalars with the effect similar to Enumerable#reject
Feature #16374:
Object#nullify to provide scalars with the effect similar to Enumerable#reject
Status:
Open
Assignee:
-
Target version:
-
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