public
Last active

Fun with Metaprogramming in Ruby

  • Download Gist
meta.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.