Skip to content

Instantly share code, notes, and snippets.

@Ejhfast
Created December 29, 2010 15:14
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Ejhfast/758608 to your computer and use it in GitHub Desktop.
Fun with Metaprogramming in Ruby
class FStore
attr_accessor :dynamic_methods
def initialize
@dynamic_methods = []
end
def mix(s1, s2, s3, &block)
name = "#{s1.to_s}_#{s2.to_s}_#{s3.to_s}".to_sym
self.send(name) {|a,b| send(s1, send(s2,a), send(s3,b))}
end
def method_missing(symbol, &block)
if block_given?
self.class.send :define_method, symbol, &block
else
bdy = proc {|*x| symbol}
self.class.send :define_method, symbol, bdy
end
@dynamic_methods << symbol
symbol
end
end
e = FStore.new
# Define a bunch of methods dynamically
e.double {|x| 2*x}
e.triple {|x| 3*x}
e.square {|x| x**2}
e.plus {|x,y| x + y}
# Mix a few methods
e.mix(:plus, :double, :triple)
puts "All e's new methods:"
e.dynamic_methods.each {|x| puts "\t#{x.to_s}"}
puts "\nEval: e.plus_double_triple(2,3)"
puts e.plus_double_triple 2, 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment