Last active
August 29, 2015 14:07
-
-
Save hzamani/c446bea100e0c55b6972 to your computer and use it in GitHub Desktop.
Try to have higher order messages (HOM) 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
module Messaging | |
def method_missing(name, *args, &block) | |
each do |item| | |
item.send(name, *args, &block) | |
end | |
end | |
def compose(op) | |
case op | |
when Symbol | |
each(&op) | |
when Proc | |
each { |x| op.(x) } | |
else | |
raise TypeError | |
end | |
end | |
def call(op) | |
compose(op) | |
end | |
def [](other) | |
compose(other) | |
end | |
def |(other) | |
compose(other) | |
end | |
def **(other) | |
compose(other) | |
end | |
end | |
module Curring | |
def |(arg) | |
curry.call(arg) | |
end | |
def **(arg) | |
curry.call(arg) | |
end | |
end | |
Enumerator.include Messaging | |
Proc.include Curring | |
# Now we can do: | |
(1..10).select.odd? | |
# which with no hack was: | |
(1..10).select(&:odd?) | |
divisible_by = ->(m,n) { n % m == 0 } | |
(1..10).select ** divisible_by ** 3 | |
# was | |
(1..10).select { |n| divisible_by(3,n) } | |
# or this :P | |
(1..10).select { |n| n % 3 == 0 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
** used because it has right to left associativity