Skip to content

Instantly share code, notes, and snippets.

@erikpukinskis
Created April 18, 2011 20:56
Show Gist options
  • Save erikpukinskis/926156 to your computer and use it in GitHub Desktop.
Save erikpukinskis/926156 to your computer and use it in GitHub Desktop.
My attempt at Lisp CLOS-style method definitions in Ruby
# By default, Ruby invokes class methods based on the number of parameters, ignoring
# the parameter type. I was curious if I could implement the method invocation pattern
# used in Lisp's CLOS, where you can have multiple methods that each accepts the same
# number of paraemters, but with different types.
#
# Needs Ruby 1.9
class Object
def self.defm(sym, *classes, &block)
@defm_methods ||= {}
@defm_methods[sym] ||= {}
@defm_methods[sym][classes] = block
define_method sym do |*params|
self.class.defm_methods[sym].each do |classes,proc|
if classes == params.map(&:class)
params.inject(proc.curry) {|proc,param| proc[param]}
end
end
end
end
def self.defm_methods
@defm_methods
end
end
# Example:
class Onion
def dice
puts "dicing!"
end
end
class Bread
def slice
puts "slicing!"
end
end
class Chef
defm :prep, Onion do |onion|
onion.dice
end
defm :prep, Bread do |bread|
bread.slice
end
end
chef = Chef.new
chef.prep(Bread.new)
chef.prep(Onion.new)
# Output:
#
# slicing!
# dicing!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment