Last active
August 29, 2015 14:06
-
-
Save baweaver/e77f80e4a84925ff0044 to your computer and use it in GitHub Desktop.
Pipe an object through a block only if condition is true. Like the pipe which simply yields self.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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