Skip to content

Instantly share code, notes, and snippets.

@0x0dea
Created June 28, 2015 04:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0x0dea/f2ac964c4cedbc90bb6d to your computer and use it in GitHub Desktop.
Save 0x0dea/f2ac964c4cedbc90bb6d to your computer and use it in GitHub Desktop.
Pseudo-class composition in Ruby.
module Composable
extend self
def extended klass
klass.send :attr_reader, :val
end
def method_missing klass
f, g = self, const_get(klass)
Class.new do
define_method(:initialize) do |n|
@val = f.new(g.new(n).val).val
end
end.extend Composable
end
end
class Succ
extend Composable
def initialize n
@val = n.succ
end
end
class Twice
extend Composable
def initialize n
@val = n * 2
end
end
(Twice . Succ . Twice).new(10).val # => 42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment