Last active
March 1, 2019 05:20
-
-
Save jtzero/979779fcc841722e4cfdb2b26fa36c38 to your computer and use it in GitHub Desktop.
elixir like pipes in ruby
This file contains hidden or 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
# asdf | |
#=> nil | |
# [3] pry(main)> 'asdf' >> pipeto(:puts, 'asdff') | |
# asdf | |
# asdff | |
#=> nil | |
# [4] pry(main)> 'asdf' >> | |
# -> x { x + 'q' } >> | |
# -> x { x + 'w' } | |
# asdfqw | |
# [5] pry(main)> 'asdf' >> | |
# -> x { [x, 'q'] } >> | |
# -> x { x + ['w'] } >> | |
# File.pipeto(:join) | |
#=> "asdf/q/w" | |
# [6] pry(main)> 'asdf' >> | |
# -> x { [x, 'q'] } >> | |
# -> x { x + ['w'] } >> | |
# File.pipeto(:join, 'n') | |
#=> "asdf/q/w/n" | |
# [6] pry(main)> 'asdf' >> | |
# -> x { [x, 'q'] } >> | |
# -> x { x + ['w'] } >> | |
# File.method(:join), 'n' | |
#=> "asdf/q/w/n" | |
# [8] pry(main)> 'asdf' >> | |
# -> x { [x, 'q'] } >> | |
# -> x { x + ['w'] } >> | |
# -> x { File.join(x, 'n') } | |
# => "asdf/q/w/n" | |
# [9] pry(main)> 'asdf' .>> | |
#=> ArgumentError: wrong number of arguments (given 0, expected 1+) | |
# | |
# [10] pry(main)> 'asdf' >> | |
# pry(main)* -> x { [x, 'w'] } .>>( | |
# pry(main)* File.method(:join), 'n' | |
# pry(main)* ) | |
#ArgumentError: wrong number of arguments (given 2, expected 1) | |
#from (pry):27:in `>>' | |
# | |
# with detructuring | |
# [10] pry(main)> 'asdf' >> | |
# pry(main)> -> x { [x, 'q'] } >> | |
# pry(main)> lambda {|(x,y)| File.join(x,y) } | |
# => "x/y" | |
# | |
class Object | |
def >>(func_or_symbol, *args) | |
if func_or_symbol.is_a? Symbol | |
method(func_or_symbol)[self, *args] | |
else | |
prc = func_or_symbol.to_proc | |
if prc.arity == [self, *args].size | |
prc[self, *args] | |
else | |
prc.curry[self, *args] | |
end | |
end | |
end | |
# for currying | |
# to handle somthing like | |
# File .>> (:join, 'n') #=> File.join(File, 'n') | |
# shorthand for | |
# -> x { File.join(x, 'n') } | |
# or | |
# 'asdf' .>> File.method(:join), 'n' | |
# @see [1], [5], [6] | |
def pipeto(sym, *args) | |
lambda {|x| method(sym)[x, *args] } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment