Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pipe an object through a block only if condition is true. Like the pipe which simply yields self.
class Object
def conditional_pipe(condition, &block)
condition ? yield(self) : self
end
def true_tap(&block)
self && yield(self)
self
end
def false_tap(&block)
self || yield(self)
self
end
end
"foobar".conditional_pipe(true) { |s| s.sub(/foo/, 'baz') }
#=> "bazbar"
"foobar".conditional_pipe(false) { |s| s.sub(/foo/, 'baz') }
#=> "foobar"
true.false_tap { |v| puts v }
#=> true
true.true_tap { |v| puts v }
# true
#=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.