Fun with Metaprogramming in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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