Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@solnic
Last active December 26, 2015 23:29
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solnic/85215f57c3ee8d669363 to your computer and use it in GitHub Desktop.
Save solnic/85215f57c3ee8d669363 to your computer and use it in GitHub Desktop.
Ruby object that has "functions" rather than methods
class Function
attr_reader :name, :fn
class Composed
attr_reader :left, :right
def initialize(left, right)
@left = left
@right = right
end
def call(input)
left.(right.(input))
end
end
def initialize(name, fn)
@fn = fn
end
def *(other)
Composed.new(self, other)
end
def call(input)
fn.(input)
end
end
class FunctionObject
def self.method_added(name)
return if @busy
meth = instance_method(name)
defn(name, meth)
end
def self.defn(name, meth)
@busy = true
undef_method(name)
define_method(name) do
Function.new(name, meth.bind(self))
end
@busy = false
end
end
RSpec.describe FunctionObject do
it 'has functions' do
things = Class.new(FunctionObject) do
def sort(data)
data.sort
end
def upcase(data)
data.map(&:upcase)
end
end.new
data = %w(foo bar)
expect((things.sort * things.upcase).(data)).to eql(%w(BAR FOO))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment