Created
April 10, 2012 00:50
-
-
Save JCallicoat/2347673 to your computer and use it in GitHub Desktop.
Clojure's -> in Ruby (not that you'd ever really do it :P)
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
#!/usr/bin/ruby | |
# http://clojuredocs.org/clojure_core/clojure.core/-%3E | |
# http://clojuredocs.org/clojure_core/clojure.core/-%3E%3E | |
def thread_first(val, *args) | |
args.inject(val) { |acc, arg| | |
if val.is_a? Hash | |
acc = acc[arg] | |
else | |
if arg.is_a? Array | |
if arg.last.is_a? Proc | |
acc = acc.send(arg[0], *arg[1...-1], &arg[-1]) | |
else | |
acc = acc.send(arg[0], *arg[1..-1]) | |
end | |
else | |
acc = acc.send(arg) | |
end | |
end | |
} | |
end | |
p thread_first("a b c d", | |
:upcase, | |
[:sub, "A", "X"], | |
[:split, " "], | |
:first) | |
# => "X" | |
# no built in lazy sequences, so cheating a bit with a fixed range | |
p thread_first(0..100, | |
:to_a, | |
[:map, proc {|i| i*i}], | |
[:select, proc {|i| i.even?}], | |
[:take, 10], | |
[:reduce, :+]) | |
# => 1140 | |
person = { | |
:name => "Mark Volkmann", | |
:address => { | |
:street => "644 Glen Summit", | |
:city => "St. Charles", | |
:state => "Missouri", | |
:zip => 63304 | |
}, | |
:employer => { | |
:name => "Object Computing, Inc.", | |
:address => { | |
:street => "12140 Woodcrest Executive Drive, Suite 250", | |
:city => "Creve Coeur", | |
:state => "Missouri", | |
:zip => 63141 | |
} | |
} | |
} | |
p thread_first(person, :employer, :address, :city) | |
# => "Creve Coeur" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment